preg_replace内的函数调用问题

时间:2009-12-20 16:29:19

标签: php variables preg-replace

不起作用,调用函数时$ 1值会丢失:

echo preg_replace('"\b(http://\S+)"', '<a href="$1">'.findTopDomain('$1').'</a>', $text);

工作正常,输出:stackoverflow.com

echo preg_replace('"\b(http://\S+)"', '<a href="$1">'.findTopDomain('http://stackoverflow.com/questions/ask').'</a>' , $text);

我需要将$ 1值发送到preg_replace中的函数。 我做错了什么?

2 个答案:

答案 0 :(得分:2)

您需要设置e modifier以执行替换表达式:

preg_replace('"\b(http://\S+)"e', '"<a href=\\"$1\\">".findTopDomain("$1")."</a>"', $text)

请注意,您的替换现在必须是有效的PHP表达式。在这种情况下,表达式将被评估为:

"<a href=\"$1\">".findTopDomain("$1")."</a>"

不要忘记至少使用htmlspecialchars来逃避输出:

preg_replace('"\b(http://\S+)"e', '"<a href=\\"".htmlspecialchars("$1")."\\">".htmlspecialchars(findTopDomain("$1"))."</a>"', $text)

答案 1 :(得分:2)

您在寻找php_replace_callback()吗?

  

执行正则表达式搜索并使用回调替换