2009-12-20 85 views
0

功能不能正常工作,调用函数时的$ 1值丢失:问题里面的preg_replace

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); 

我需要发在preg_replace中函数的$ 1值。 我在做什么错?

回答

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)