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