繁体   English   中英

正则表达式preg_match PHP

[英]regular expression preg_match PHP

我正在尝试使内容在两个大括号或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);

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

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

谢谢

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

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

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

暂无
暂无

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

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