[英]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.