简体   繁体   English

正则表达式向前和向后查找,并在某些字符之间进行匹配

[英]Regexp lookahead and lookbehind and match between certain characters

Currently I have this regexp to detect strings between double curly brackets and it work's wonderfully. 目前,我有此正则表达式来检测双大括号之间的字符串,并且效果很好。

$str = "{{test}} and {{test2}}";
preg_match_all('/(?<={{)[^}]*(?=}})/', $str, $matches);
print_r($matches);

Returns:
Array
(
[0] => Array
    (
        [0] => test
        [1] => test2
    )

)

Now I need to expand it to only match stuff between ]] and [[ 现在,我需要扩展它以仅匹配[]和[[

$str = "{{dont match}}]]{{test}} and {{test2}}[[{{dont match}}";

I've been trying to modify the regex but the lookahead and lookbehind is making it too difficult for me. 我一直在尝试修改正则表达式,但是前瞻性和后向性对我来说太难了。 How can I get it to match stuff inside ]] and [[ only? 如何获得与[]和[[仅匹配?

Also I would like to match the whole string between ]] and [[ and then I would like to match each individual string between {{ }} inside it. 另外,我想匹配]]和[[之间的整个字符串,然后匹配其中{{}}之间的每个单独的字符串。

For example: 例如:

$str = "{{dont match}}]]{{test}} and {{test2}}[[{{dont match}}";

Would return:
Array
(
[0] => Array
    (
        [0] => {{test}} and {{test2}}
        [1] => test
        [2] => test2
    )

)

Piggyback using preg_replace_callback : 使用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]);

Output: 输出:

Array
(
    [0] => test
    [1] => test2
)

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

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