我坐了大约 2 个小时试图从字符串中提取参数。不管它有多少参数。
考虑这个(例子),
$template = "/category/(:any)/(:any)/(:any)/";
$input = "/category/username/category-id/2";
And I would like an array of parameters to be like this,
Array (
[0] => username
[1] => category-id
[2] => 2
)
所以,我从
$replacements = array(
'(:any)' => '.+(?=/|$)',
);
$str = '/category/(:any)/(:any)/(:any)';
$str = str_replace(array_keys($replacements), array_values($replacements), $str);
$input = '/category/username/category-id/2';
$pattern = '~^' . $str . '$~';
preg_match($pattern, $input, $matches);
print_r($matches);
// That prints Array ( [0] => /category/username/category-id/2 )
但现在我坚持正确的参数提取。首先想到的是在两个字符串之间找到相似的值并将它们删除。然后删除(:any)
和/
。
$template = "/category/(:any)/(:any)/(:any)/";
$input = "/category/username/category-id/2";
问题是,依赖explode()
.
所以问题是:(看看第一个代码示例):我怎样才能正确地使用正则表达式来实现这一点,这将匹配并正确放入参数$matches
?