Here, you have your function:
<?php
$str = "/mypage/20/my-slug";
$subject = "/mypage/{id}/{slug}";
function getQueryParameters($url, $pattern)
{
// Find first parameter:
$pos=strpos($pattern, '{');
if($pos===false)
{
return [];
}
$prefix=substr($pattern, 0, $pos);
// Check for route
if(substr($url, 0, $pos)!=$prefix)
{
return false;
}
$curlyBracesRegex='/'
. '\{' // One {
. '([^\s}]+)' // something inside curly braces, e.g. {foo}
// Excluding whitespaces (\s)
. '\}' // One }
. '/';
preg_match_all($curlyBracesRegex, $pattern, $matches);
$parameters=[];
foreach ($matches[0] as $index => $match)
{
$parameters[]=$matches[1][$index];
}
$matches=explode('/', substr($url, $pos));
$queryParameters=array_combine($parameters, $matches);
return $queryParameters;
}
print_r(getQueryParameters($str, $subject));
You can test here: http://sandbox.onlinephpfunctions.com/code/8646e13bfc5a2b9ed5e2a5a2a9b9ddf1b0ab9db5