在regex中重用匹配的组

时间:2013-01-14 13:05:39

标签: php regex

我正在努力匹配: “{{loop(something)}}”和第一个{{/ loop(that something)}}

之间的所有内容

文字示例:

{{ LOOP data }}
  <span> Member key       =  {{.key}}  </span>
  <span> Member value     =  {{.}}     </span>
  <span> Member member    =  {{name}}  </span>
  <span> Iteration number = {{.counter}} </span>
{{ /LOOP data }} 

这是正则表达式不起作用:

/\{\{\s+loop\s+(.+?)\s+\}\}([\w\W]+?)\{\{\s+\/loop\s$1\s+\}\}/i

正如您所看到的,我正在尝试将第一个匹配的组重复使用“$ 1”:我缺少什么?

Php代码如下:

$text = '
{{ LOOP data }}
  <span> Member key       =  {{.key}}  </span>
  <span> Member value     =  {{.}}     </span>
  <span> Member member    =  {{name}}  </span>
  <span> Iteration number = {{.counter}} </span>
{{ /LOOP data }}   
';

preg_match('/\{\{\s+loop\s+(.+?)\s+\}\}([\w\W]+?)\{\{\s+\/loop\s\1\s+\}\}/i', $text, $match);
print_r($match);
die;

1 个答案:

答案 0 :(得分:5)

我相信你想要\1,而不是$1

更多信息:http://www.regular-expressions.info/brackets.html#usebackrefinregex