递归BBCode解析

cas*_*raf 2 php regex bbcode

我正试图在我的脚本中解析BBCode.现在,它无缝地工作,直到我尝试缩进BBCode不仅仅是粗体或下划线 - 例如剧透,网址,字体大小等 - 然后它搞砸了.这是我的代码:

function parse_bbcode($text) {
    global $db;
    $oldtext = $text;
    $bbcodes = $db->select('*', 'bbcodes');
    foreach ($bbcodes as $bbcode) {
        switch ($bbcode->type) {
            case 'simple': {
                $find = '{content}';
                $replace = '${1}';
                $text = preg_replace(
                    '/\['.$bbcode->tag.'\](.+)\[\/'.$bbcode->tag.'\]/i',
                    str_replace($find, $replace, $bbcode->html),
                    $text);
                    break;
            }
            case 'property':
            case 'options': {
                $find = array ( '{property}', '{content}' );
                $replace = array ( '${1}', '${2}' );
                $text = preg_replace(
                    '/\['.$bbcode->tag.'\=(.[^\"]*)\](.+)\[\/'.$bbcode->tag.'\]/i',
                    str_replace($find, $replace, $bbcode->html),
                    $text);
                    break;
            }
        }
    }
    return $text;
}
Run Code Online (Sandbox Code Playgroud)

现在我的猜测是RegEx不喜欢模式中的递归.我怎样才能改进它?示例$ bbcode对象是这样的:

stdClass::__set_state(array(
   'id' => '2',
   'name' => 'Italic',
   'type' => 'simple',
   'tag' => 'i',
   'button_image' => NULL,
   'button_text' => '<i>I</i>',
   'options' => '',
   'prompt' => NULL,
   'html' => '<i>{content}</i>',
   'order' => '1',
))
stdClass::__set_state(array(
   'id' => '3',
   'name' => 'URL',
   'type' => 'property',
   'tag' => 'url',
   'button_image' => NULL,
   'button_text' => 'http://',
   'options' => '',
   'prompt' => 'URL address',
   'html' => '<a href="{property}">{content}</a>',
   'order' => '4',
))
Run Code Online (Sandbox Code Playgroud)

Cle*_*man 6

正如gordon在评论中所说,PHP有一个BBCode解析器,所以没有理由重新发明轮子.

本机解析器虽然是PECL包,但您必须安装它.如果这不是一个选项(例如由于共享托管),还有一个PEAR包:http://pear.php.net/package/HTML_BBCodeParser

除此之外,您还可以使用BB代码源代码查看论坛,并使用其解析器或改进它.http://www.bbcode.org/implementations.php上还列出了几个PHP实现