简体   繁体   English

正则表达式preg_match PHP

[英]regular expression preg_match PHP

I am trying to get contents between two curly brackets or Smarty tag. 我正在尝试使内容在两个大括号或Smarty标签之间。 I want to get variables with smarty function only, ignoring if 's, etc. 我只想使用smarty函数获取变量,而忽略if ,等等。

Here are the sample string tags: 以下是示例字符串标签:

{{$variable|lower}} [should be matched] {{$variable|lower}} [应匹配]

{{$variable|escape:javascript}} [should be matched] {{$variable|escape:javascript}} [应匹配]

{{$variable|str_replace:"search":"replace"}} [should be matched] {{$variable|str_replace:"search":"replace"}} [应匹配]

{{if $test eq "test"}} [should NOT be matched] {{if $test eq "test"}} [ 应该匹配]

{{section name=foo start=10 loop=20 step=2}} [should NOT be matched] {{section name=foo start=10 loop=20 step=2}} [ 应该匹配]

If I do this 如果我这样做

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

It gets everything within the brackets. 它使所有内容都在方括号内。

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

This only gets "variable|escape". 这只会得到“变量|转义”。

Please help with correct regular expression. 请提供正确的正则表达式帮助。

Thanks 谢谢

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

I could be wrong, but wouldn't simply: 我可能是错的,但不会简单地:

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

do the trick, where $matches[1] will hold the variables. 做到这一点,其中$matches[1]将保存变量。 If the files contain carriage returns (windows' \\r\\n), try '/\\{\\{(\\$[^|]+)\\|[^}]+\\}\\}/s' , with the s modifier 如果文件包含回车符(windows'\\ r \\ n),请尝试使用s修饰符'/\\{\\{(\\$[^|]+)\\|[^}]+\\}\\}/s'

to include matches like: {{$var}} 包括以下匹配项: {{$var}}

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

returns: 返回:

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 => '',
  ),
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM