正则表达式preg_match PHP

时间:2012-08-07 14:26:45

标签: php regex

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

以下是示例字符串标记:

{{$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);

这只是“变量”逃脱。

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

由于

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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 => '',
  ),
)
相关问题