$regex = '/\[b\](.*?)\[\/b\]/is';
$string = '[b][b][b]string[/b][/b][/b]';
这只会匹配到第一个[/ b],所以如果我使用这个正则表达式将这个bbcode转换为HTML,我将最终得到这个:
string[/b][/b]
我正在使用PHP preg_replace,我最终只能使用string
,所以3个html粗体标记。
答案 0 :(得分:3)
对于这种肮脏的案件:
this [b]is [b]a[/b][/b] test [b]string[/b]
递归解决方案有效:
\[b](?:(?:(?!\[b]).)*?|(?R))*\[/b]
PHP代码:
$str = 'this [b]is [b]a[/b][/b] test [b]string[/b]';
echo preg_replace_callback('~\[(\w+)](?:(?:(?!\[\1]).)*?|(?R))*\[/(\1)]~', function($m) {
return "**".preg_replace("~\[/?$m[1]]~", '', $m[0])."**";
}, $str);
输出:
this **is a** test **string**
答案 1 :(得分:1)