我有一个包含以下模式的字符串“[link:activate / $ id / $ test_code]”我需要在模式[link .....]中获取单词activate,$ 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
)
)
答案 0 :(得分:0)
这是你在找什么?
/\[link:([\w\d]+)\/(\$[\w\d]+)\/(\$[\w\d]+)\]/
编辑:
你的表达问题也是这个部分:
(\/\$[a-z\_]+)+
虽然您重复了该组,但该匹配仅返回一个,因为它仍然只是一个组声明。正则表达式不会为你创造匹配的组号(不是我以前见过的)。
答案 1 :(得分:0)
试试这个:
$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';