给定字符串$str = 'aa {{asd}} bla {{{888 999}} {555} 777 uiii {{-i {{qw{er}}';
需要在最近的开 - 闭双花括号之间进行所有出现。
理想的结果:
如果尝试:preg_match_all('#\{\{(.*?)\}\}#', $str, $matches);
当前输出:
但是,这些事件不在最近的双花括号之间。
问题是:适合的模式是什么?
答案 0 :(得分:3)
您可以使用此模式:
\{\{(?!\{)((?:(?!\{\{).)*?)\}\}
这里的诀窍是使用像(?!\{\{)
这样的否定前瞻来避免匹配嵌套括号。
\{\{ # match {{
(?!\{) # assert the next character isn't another {
(
(?: # as few times as necessary...
(?!\{\{). # match the next character as long as there is no {{
)*?
)
\}\} # match }}
答案 1 :(得分:1)
正则表达式: (?<=\{{2})(?!\{)[\s\w\{]+(?=\}\})
(?=\}\})
前面应该包含双花括号
(?<=\{{2})
后面应该包含花括号
(?!\{)
不应该在两个匹配的
PHP代码:
$str = 'aa {{asd}} bla {{{888 999}} {555} 777 uiii {{-i {{qw{er}}';
preg_match_all("/(?<=\{{2})(?!\{)[\s\w\{]+(?=\}\})/",$str,$matches);
print_r($matches);
<强>输出:强>
Array
(
[0] => Array
(
[0] => asd
[1] => 888 999
[2] => qw{er
)
)