递归BBCode解析 [英] Recursive BBCode Parsing
问题描述
我正在尝试在我的脚本中解析 BBCode.现在,它无缝地工作,直到我尝试缩进不仅仅是粗体或下划线的 BBCode - 例如剧透、url、字体大小等 - 然后它搞砸了.这是我的代码:
I'm trying to parse BBCode in my script. Now, it works seamelessly, until I try to indent BBCode that's more than just bold or underline - such as spoiler, url, font size, etc. - then it screws up. Here's my code:
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 对象如下所示:
Now my guess is that the RegEx doesn't like the recursiveness in the pattern. How can I improve it? A sample $bbcode object is as such:
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',
))
推荐答案
正如 gordon 在评论中所说的 PHP 有一个 BBCode 解析器,所以没有理由重新发明轮子.
As gordon said in comments PHP has a BBCode parser, so no reason to reinvent the wheel.
虽然本机解析器是一个 PECL 包,因此您必须安装它.如果这不是一个选项(例如由于共享托管),还有一个 PEAR 包:http://pear.php.net/package/HTML_BBCodeParser
The native parser is a PECL package though, so you will have to install it. If that's not an option (for instance due to shared hosting), there is also a PEAR package: http://pear.php.net/package/HTML_BBCodeParser
除此之外,您还可以查看使用 BB 代码源代码的论坛,并使用他们的解析器或对其进行改进.http://www.bbcode.org/implementations.php 还列出了几个 PHP 实现
In addition to those, you can take a look at forums using BB code source code, and either use their parser, or improve it. There is also several PHP implementations listed at http://www.bbcode.org/implementations.php
这篇关于递归BBCode解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!