I'm sitting about 2 hours trying to extract parameters from a string. No matter how many parameters it has.
Consider this (example),
$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
)
So, I've started from,
$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 )
But now I'm stuck with proper parameter extracting. The very first that that comes to mind is to find similar values between two strings and remove them. Then remove (:any) and /.
$template = "/category/(:any)/(:any)/(:any)/";
$input = "/category/username/category-id/2";
The problem is that, it will require a lot of extra work relying on explode().
So the question is : (take a look at the first code example):
How can I properly achieve that using a regular expression, that would match and properly put parameters in $matches?