获取最近的双括号之间的所有出现

时间:2017-04-09 15:19:13

标签: php regex

给定字符串$str = 'aa {{asd}} bla {{{888 999}} {555} 777 uiii {{-i {{qw{er}}';

需要在最近的开 - 闭双花括号之间进行所有出现。

理想的结果:

  • ASD
  • 888 999
  • QW {ER

如果尝试:preg_match_all('#\{\{(.*?)\}\}#', $str, $matches);

当前输出:

  • ASD
  • {888 999
  • -i {{qw {er

但是,这些事件不在最近的双花括号之间。

问题是:适合的模式是什么?

2 个答案:

答案 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)

Regex demo

正则表达式: (?<=\{{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
        )

)
相关问题