我正在尝试在我的脚本中解析BBCode。现在,它可以无缝运行,直到我尝试缩进更多的BBCode,例如spoiler、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;
}
我猜测正则表达式在模式的递归上有问题。如何改进它?样例 $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',
))