调用函数PREG_REPLACE

时间:2016-03-10 00:26:23

标签: php preg-replace preg-replace-callback

具有安全性和弃用功能;在查找和替换中调用函数的最简单,最安全的方法是什么?

可以在内容[album][/album], [img][/img], [youtube][/youtube], or [vimeo][/vimeo]中插入四个查找和替换模块。

使用我到目前为止放在一起的功能图像,YouTube和Vimeo是不费脑子的。专辑没那么多。我想根据传递的参数调用一个函数。

我尝试将此功能更改为preg_replace_callback并且只是嘲笑一切。还有其他选择吗?

function FormatModules($text) {
    $find = array(
        '~\[album\](.+?)\[/album\]~s',
        '~\[img width=(.*?) height=(.*?) alt=(.*?)\](https?://.*?\.(?:jpg|jpeg|gif|png))\[/img\]~s',
        '~\[youtube\](.+?)\[/youtube\]~s',
        '~\[vimeo\](.+?)\[/vimeo\]~s'
    );
    $replace = array(
        'GenerateAlbum($1)', // call a PHP function
        '<img src="$4" width="$1" height="$2" alt="$3" />',
        '<iframe src="http://www.youtube.com/embed/$1"></iframe>',
        '<iframe src="https://player.vimeo.com/video/$1"></iframe>'
    );
    return preg_replace($find, $replace, $text);
}

1 个答案:

答案 0 :(得分:0)

如果您要在多个替换项上调用函数,或者希望设置脚本以供将来修改,以便可以在替换参数上调用函数,则可以使用preg_replace_callback_array()

否则,我想说一个preg_replace_callback()涉及$find$replace的前几个元素,然后在其余元素上运行preg_replace()

代码:(Demo

function GenerateAlbum($match) {
    return "<div class=\"album\>Do whatever: " . strtoupper($match[1]) . "</div>";
}

function FormatModules($text) {
    $text = preg_replace_callback('~\[album\](.+?)\[/album\]~s', "GenerateAlbum", $text);
    $find = array(
        '~\[img width=(.*?) height=(.*?) alt=(.*?)\](https?://.*?\.(?:jpg|jpeg|gif|png))\[/img\]~s',
        '~\[youtube\](.+?)\[/youtube\]~s',
        '~\[vimeo\](.+?)\[/vimeo\]~s'
    );
    $replace = array(
        '<img src="$4" width="$1" height="$2" alt="$3" />',
        '<iframe src="http://www.youtube.com/embed/$1"></iframe>',
        '<iframe src="https://player.vimeo.com/video/$1"></iframe>'
    );
    return preg_replace($find, $replace, $text);
}

echo FormatModules("[vimeo]test1[/vimeo]\n\n[album]test2[/album]\n\njust text\n\n[img width=50 height=100 alt='sumpin good']http://www.example.com/image.gif[/img]\n\n[youtube]test3[/youtube]");

输出:

<iframe src="https://player.vimeo.com/video/test1"></iframe>

<div class="album\>Do whatever: TEST2</div>

just text

<img src="http://www.example.com/image.gif" width="50" height="100" alt="'sumpin good'" />

<iframe src="http://www.youtube.com/embed/test3"></iframe>