1

我正在尝试获取两个大括号或Smarty标签之间的内容。我只想用 smarty 函数获取变量,忽略if's 等。

以下是示例字符串标签:

{{$variable|lower}}[应该匹配]

{{$variable|escape:javascript}}[应该匹配]

{{$variable|str_replace:"search":"replace"}}[应该匹配]

{{if $test eq "test"}}[不应匹配]

{{section name=foo start=10 loop=20 step=2}}[不应匹配]

如果我这样做

preg_match_all('/{{\$?(\w+?[\W\w]*?)}}/',$str,$matches)

它得到括号内的所有内容。

preg_match_all('/{{\$?(\w+?\W*?\w*?)}}/',$str,$matches);

这只会得到“变量|转义”。

请帮助正确的正则表达式。

谢谢

4

2 回答 2

0

使用这个正则表达式\{\{.*?\|.*.+?\}\}

于 2012-08-07T14:31:40.990 回答
0

我可能是错的,但不会简单地:

preg_match_all('/\{\{(\$[^|]+)\|[^}]+\}\}/',$str,$matches);

做的伎俩,哪里$matches[1]将保存变量。如果文件包含回车符(windows'\r\n),请尝试'/\{\{(\$[^|]+)\|[^}]+\}\}/s'使用s修饰符

包括以下匹配:{{$var}}

//{{$var|foo}} {{$varbar}} bar  as test string
preg_match_all('/\{\{(\$[^|}]+)(\|[^}]+|)\}\}/s',$str,$matches);
//shorter still:
preg_match_all('/\{\{(\$[^|}]+)\|?[^}]*\}\}/s',$str,$matches);

返回:

array (
  0 => 
  array (
    0 => '{{$var|foo}}',
    1 => '{{$varbar}}',
  ),
  1 => 
  array (
    0 => '$var',
    1 => '$varbar',
  ),
  2 => //not in the array when using the second pattern
  array (
    0 => '|foo',
    1 => '',
  ),
)
于 2012-08-07T14:39:05.117 回答