【发布时间】:2011-10-10 00:48:07
【问题描述】:
我正在尝试在我的脚本中解析 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',
))
【问题讨论】:
-
没什么。我不知道。把这个作为答案怎么样,这样我就可以标记它了
-
我在下面添加了一些指向 Clement 答案的链接。请随意接受这一点:)
-
对于任何寻找的人,我想添加我编写的库,这是目前我能找到的最好的库:github.com/thunderer/Shortcode