递归BBCode解析

时间:2011-07-21 08:23:36

标签: 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;
}

现在我的猜测是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',
))

2 个答案:

答案 0 :(得分:6)

正如戈登在评论PHP has a BBCode parser, so no reason to reinvent the wheel中所说。

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

除此之外,您还可以使用BB代码源代码查看论坛,并使用其解析器或改进它。在http://www.bbcode.org/implementations.php

列出了几个PHP实现

答案 1 :(得分:0)

使用正则表达式正确解析BBcode是非繁琐的。代码可以嵌套。 CODE标记可能包含BBCode,解析器必须忽略它们。某些标签可能不会出现在其他标签内。然而,它可以做到。我最近彻底检查了FluxBB开源论坛软件的BBCode解析器。您可能希望在操作中查看它:

New 2011 FluxBB Parser

请注意,此新解析器尚未合并到FluxBB代码库中。