匹配

时间:2017-03-04 15:57:10

标签: php regex preg-replace preg-match

   $regex = '/\[b\](.*?)\[\/b\]/is';

   $string = '[b][b][b]string[/b][/b][/b]';

这只会匹配到第一个[/ b],所以如果我使用这个正则表达式将这个bbcode转换为HTML,我将最终得到这个:

string[/b][/b]

我正在使用PHP preg_replace,我最终只能使用string,所以3个html粗体标记。

2 个答案:

答案 0 :(得分:3)

对于这种肮脏的案件:

this [b]is [b]a[/b][/b] test [b]string[/b]

递归解决方案有效:

\[b](?:(?:(?!\[b]).)*?|(?R))*\[/b]

Live demo

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)

您可以使用非捕获组来扩展重复次数:

(?:\[b\])+(.*?)(?:\[\/b\])+
^^^     ^^     ^^^       ^^

请参阅demo