正则表达式前瞻和后瞻和匹配某些字符

时间:2015-03-13 10:55:34

标签: php regex match

目前我有这个正则表达式来检测双花括号之间的字符串,它的工作非常好。

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

)

1 个答案:

答案 0 :(得分:2)

使用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
)
相关问题