PHP - BBCode解析器 - 使用regex和preg_replace递归[quote]

时间:2010-07-09 22:33:13

标签: php preg-replace recursion bbcode quote

我正在创建自己的bbcode解析器,当我尝试执行递归引用时,我遇到了问题。

这是我的代码:

 function forumBBCode($str){
$format_search=array(
'#\[quote=(.*?)\](.*?)\[/quote\]#is'
);

$format_replace=array(
'<blockquote class="quotearea"><i><a class="lblackbu" href="./index.php?status=userview&userv=$1">$1</a> wrote :</i><br />$2</blockquote>'
);

$str=preg_replace($format_search, $format_replace, $str);
$str=nl2br($str);
return $str;
}

我必须添加/编辑以执行递归引用? 换句话说,当报价在另一个报价中时......

欢呼和tnx的帮助

2 个答案:

答案 0 :(得分:4)

这是一个古老的问题,但无论如何我都会发布我的解决方案ppl =]

$open = '<blockquote><span class="bold">Quote: </span><br />'; //the next few lines do the parsing for quote blocks. We 
        $close = '</blockquote>';                                      //have to do it outside the normal parsing arrays because that way does not allow nesting.

        preg_match_all ('/\[quote\]/i', $str, $matches);
        $opentags = count($matches['0']);

        preg_match_all ('/\[\/quote\]/i', $str, $matches);
        $closetags = count($matches['0']);

        $unclosed = $opentags - $closetags;
        for ($i = 0; $i < $unclosed; $i++) {
                $str .= '</blockquote>';
        }
//Do Quotes (nested)
        $str = str_replace ('[quote]', $open, $str);
        $str = preg_replace('/\[quote\=(.*?)\]/is','<blockquote class="darkbg"><span class="bold left">Quote: $1</span><br />', $str);
        $str = str_replace ('[/quote]', $close, $str);
return $str;

和平。

答案 1 :(得分:1)

请参阅PHP手册中的Recursive patterns

这也可能让您感兴趣,但更多的是技术性:Why is recursive regex not regex?