目前我有这个正则表达式来检测双大括号之间的字符串,它的工作非常好。
$str = "{{test}} and {{test2}}";
preg_match_all('/(?<={{)[^}]*(?=}})/', $str, $matches);
print_r($matches);
Returns:
Array
(
[0] => Array
(
[0] => test
[1] => test2
)
)
现在我需要扩展它以仅匹配 ]] 之间的内容]和 [[
$str = "{{dont match}}]]{{test}} and {{test2}}[[{{dont match}}";
我一直在尝试修改正则表达式,但前瞻和后视对我来说太难了。我怎样才能让它匹配里面的东西 ]] 和 [[ only?
我也想在 ]] 之间匹配整个字符串]和 [[,然后我想在其中的 {{ }} 之间匹配每个单独的字符串。
例如:
$str = "{{dont match}}]]{{test}} and {{test2}}[[{{dont match}}";
Would return:
Array
(
[0] => Array
(
[0] => {{test}} and {{test2}}
[1] => test
[2] => test2
)
)
使用 preg_replace_callback
背负:
$str = "{{dont match}}]]{{test}} and {{test2}}[[{{dont match}}";
$arr = array();
preg_replace_callback('/']'](.*?)'['[/', function($m) use (&$arr) {
preg_match_all('/(?<={{)[^}]*(?=}})/', $m[1], $arr); return true; }, $str);
print_r($arr[0]);
输出:
Array
(
[0] => test
[1] => test2
)