[英]Pattern for preg_match
我有一個包含以下模式“ [link:./.../$ id / $ test_code]”的字符串,當模式[link .....]出現時,我需要從中獲取激活字,$ id和$ test_code。
我還嘗試通過使用分組來獲取內部項目,但僅處於活動狀態,而$ test_code無法獲得$ id。 請幫助我獲取數組中的所有參數和動作名稱。
下面是我的代碼和輸出
function match_test()
{
$string = "Sample string contains [link:activate/\$id/\$test_code] again [link:anotheraction/\$key/\$second_param]]] also how the other ationc like [link:action] works";
$pattern = '/\[link:([a-z\_]+)(\/\$[a-z\_]+)+\]/i';
preg_match_all($pattern,$string,$matches);
print_r($matches);
}
Array
(
[0] => Array
(
[0] => [link:activate/$id/$test_code]
[1] => [link:anotheraction/$key/$second_param]
)
[1] => Array
(
[0] => activate
[1] => anotheraction
)
[2] => Array
(
[0] => /$test_code
[1] => /$second_param
)
)
這是你想要的?
/\\[link:([\\w\\d]+)\\/(\\$[\\w\\d]+)\\/(\\$[\\w\\d]+)\\]/
編輯:
同樣,您表達的問題是這部分: (\\/\\$[az\\_]+)+
盡管您已經重復了該組,但是該匹配將僅返回一個,因為它仍然只是一個組聲明。 正則表達式不會為您發明匹配的組號(無論如何我都沒有見過)。
嘗試這個:
$subject = <<<'LOD'
Sample string contains [link:activate/$id/$test_code] again [link:anotheraction/$key/$second_param]]] also how the other ationc like [link:action] works
LOD;
$pattern = '~\[link:([a-z_]+)((?:/\$[a-z_]+)*)]~i';
preg_match_all($pattern, $subject, $matches);
print_r($matches);
如果您需要將\\$id
和\\$test_code
分開,則可以使用以下代碼:
$pattern = '~\[link:([a-z_]+)(/\$[a-z_]+)?(/\$[a-z_]+)?]~i';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.