2017-04-09 88 views
2

鉴于串$str = 'aa {{asd}} bla {{{888 999}} {555} 777 uiii {{-i {{qw{er}}';找最接近的双括号

之间的所有事件需要得到最接近的开闭双大括号之间的所有事件。

理想的结果:

  • ASD
  • QW ER {

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

电流输出:

  • ASD
  • {888 999
  • -i {{{QW ER

不过,这些情况并不最接近双大括号之间。

问题是:这是什么适当的模式?

+0

将预期的输出是多少,如果输入中包含像'{{{a} b}}'? '{a} b'或'a} b'? –

+0

@Rawing - 在这种情况下预期的输出:'a} b' –

回答

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

Regex demo

正则表达式:(?<=\{{2})(?!\{)[\s\w\{]+(?=\}\})

(?=\}\})应该包含双花括号前面

(?<=\{{2})应包含后面

0大括号

(?!\{)不应该包含大括号后面两个一个大括号匹配

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 
     ) 

)