calling function inside preg_replace thats inside a function

大憨熊 提交于 2019-12-28 01:27:46

问题


I have some code with the a structure similar to this

           function bbcode($Text)
           { //$Text = preg_replace("/\[video\](.+?)\[\/video\]/",embed_video($1), $Text);
    return $Text;}

    function embed_video($url){
if (preg_match("/http:\/\/www.youtube.com\/watch\?v=([0-9a-zA-Z-_]*)(.*)/i", $url, $matches)) {
    return '<object width="425" height="350">'.
           '<param name="movie" value="http://www.youtube.com/v/'.$matches[1].'" />'.
           '<param name="wmode" value="transparent" />'.
           '<embed src="http://www.youtube.com/v/'.$matches[1].'&autoplay="0" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350" />'.
           '</object>';
}
    return $url;
    }

$lolcakes = "[video]http://youtube.com/id/xxxxxxpron[/video]";
$lolcakesconverted = bbcode($lolcakes);

The problem is it spits an error back at me.

Parse error: syntax error, unexpected T_LNUMBER, expecting T_VARIABLE or '$'

Have any ideas on how i can call embed_video inside of the preg_replace of the bbcode function?

Thanks!


回答1:


You can use the "e" modifier on preg_replace() (see Pattern Modifiers)

return preg_replace("/\[video\](.+?)\[\/video\]/e", "embed_video('$1')", $Text);

which tells preg_replace() to treat the second parameter as PHP code.




回答2:


try preg_replace_callback

return preg_replace_callback("/\[video\](.+?)\[\/video\]/", 'embed_video', $Text);

function embed_video($matches)
{
  return $matches[1] . 'foo';      
}


来源:https://stackoverflow.com/questions/2082207/calling-function-inside-preg-replace-thats-inside-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!