2
在分钟我:使用PHP如何将HTMLentities()应用于preg_replace()调用中的反向引用?
$Text = preg_replace("/\[code\](.*?)\[\/code\]/s", "<mytag>\\1</mytag>", $Text);
我怎样才能逃避使用htmlentities()
的索引吗?
在分钟我:使用PHP如何将HTMLentities()应用于preg_replace()调用中的反向引用?
$Text = preg_replace("/\[code\](.*?)\[\/code\]/s", "<mytag>\\1</mytag>", $Text);
我怎样才能逃避使用htmlentities()
的索引吗?
$Text = "foo [code]bla<br>bla[/code] foo";
echo preg_replace_callback('/\[code\](.*?)\[\/code\]/s', 'wrap_code', $Text);
function wrap_code($matches) {
return '<mytag>'.htmlspecialchars($matches[1]).'</mytag>';
}
正如preg_replace_callback()
documentation看到,你还可以创建回调函数内联,通过create_function()
或PHP 5.3.0的甚至使用anonymous function。
通用的做法不过是沿着此线:
$Text = "foo [code]bla<br>bla[/code] foo";
$re_bbcode = '/\[(code|b|whatever)\](.*?)\[\/\1\]/s';
echo preg_replace_callback($re_bbcode, 'wrap_code', $Text);
function wrap_code($matches) {
switch ($matches[1]) {
case 'code': $tag = 'mytag'; break;
case 'b' : $tag = 'b'; break;
default : $tag = '';
}
if ($tag != '')
return "<$tag>".htmlspecialchars($matches[2])."</$tag>";
else
return htmlspecialchars($matches[0]);
}
而且我想(我没有测量),这正则表达式可能会快一点,因为不情愿的量词不会被调用的次数超过必要:
\[(code|b|whatever)\]([^\[]+|.*?)\[\/\1\]
非常有趣,我现在已经实现它作为一个匿名函数。谢谢。 – 2010-06-06 23:18:14