簡體   English   中英

正則表達式向前和向后查找,並在某些字符之間進行匹配

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

目前,我有此正則表達式來檢測雙大括號之間的字符串,並且效果很好。

$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}}";

我一直在嘗試修改正則表達式,但是前瞻性和后向性對我來說太難了。 如何獲得與[]和[[僅匹配?

另外,我想匹配]]和[[之間的整個字符串,然后匹配其中{{}}之間的每個單獨的字符串。

例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM