2010-06-06 31 views

回答

2
$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\] 
+0

非常有趣,我现在已经实现它作为一个匿名函数。谢谢。 – 2010-06-06 23:18:14