嵌套的bb代码引用how to>


nested bb code quotes how to>

我正在使用一个非常基本的bbcode解析器。

你们能帮我解决一个问题吗?

但是当它被写为:

[quote=tanab][quote=1][code]a img{
text-decoration: none;
}[/code][/quote][/quote]

输出如下:

tanab said:
[quote=1]
a img{
    text-decoration: none;
}
[/quote] 

我该如何解决这个问题?我真的很不擅长preg_replace之类的东西。

这是我的解析器:

function bbcode($input){
$input = htmlentities($input);
$search = array(
            '/'[b'](.*?)'['/b']/is',
            '/'[i'](.*?)'['/i']/is',
            '/'[img'](.*?)'['/img']/is',
            '/'[url=(.*?)'](.*?)'['/url']/is',
            '/'[code'](.*?)'['/code']/is',
            '/'['*'](.*?)/is',
            '/''t(.*?)/is',
            '/'[quote=(.*?)'](.*?)'['/quote']/is',
);
$replace = array(
            '<b>$1</b>',
            '<i>$1</i>',
            '<img src="$1">',
            '<a href="$1">$2</a>',
            '<div class="code">$1</div>',
            '<ul><li>$1</li></ul>',
            '&nbsp;&nbsp;&nbsp;&nbsp;',
            '<div class="quote"><div class="quote-writer">$1 said:</div><div class="quote-body">$2</div></div>',
);
return preg_replace($search,$replace,$input);

}

这个可以用递归正则表达式来适应:

 '/'[quote=(.*?)'](((?R)|.*?)+)'['/quote']/is'

这将至少确保输出div不会被错误地嵌套。但是,您仍然需要运行regex两次或三次才能捕获所有引号块。

否则需要用preg_replace_callback重写代码。这个问题我已经懒得展示了,因为这个问题已经出现了几十次了(试试网站搜索吧!),之前已经解决了,等等。