在函数内部的preg_replace中调用函数

时间:2010-01-17 19:02:33

标签: php function preg-replace syntax-error

我有一些类似于

的结构的代码
           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);

问题是它向我吐了一个错误。

解析错误:语法错误,意外T_LNUMBER,期待T_VARIABLE或'$'

对于我如何在bbcode函数的preg_replace中调用embed_video有什么想法?

谢谢!

2 个答案:

答案 0 :(得分:31)

尝试preg_replace_callback

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

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

答案 1 :(得分:30)

您可以在preg_replace()上使用“e”修饰符(参见Pattern Modifiers

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

告诉preg_replace()将第二个参数视为PHP代码。

相关问题