我正在尝试解析脚本中的BBCode。现在,它可以无缝地工作了,直到我尝试缩进BBCode,而不仅仅是粗体或下划线,比如扰流,url,字体大小等等,它就搞砸了。下面是我的代码:
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',
))发布于 2011-07-21 16:28:35
正如戈登在评论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实现。
发布于 2011-07-21 22:32:39
使用正则表达式正确解析BBcode并非易事。代码可以是嵌套的。CODE标记可能包含解析器必须忽略的BBCodes。某些标签不能出现在其他标签内。然而,这是可以做到的。我最近检查了FluxBB开源论坛软件的BBCode解析器。您可能想要在实际操作中检查它:
New 2011 FluxBB Parser
注意,这个新的解析器还没有合并到FluxBB代码库中。
https://stackoverflow.com/questions/6773192
复制相似问题