我需要检查路由是否存在,数组中的路由是字符串,路由存储在字符串数组中,例如paths[0] = 'posts/all/{postID}' (注意花括号和参数名称)。假设用户输入网址为“post/all/4”的网站。如何将浏览器中输入的 url 与带有大括号和参数名称的 url 进行匹配,如果数组中有一个匹配,则调用一个函数,该函数仅获取大括号中的参数之前的 url 部分,并传递大括号内的变量及其该函数的原始名称(可以是数组,例如 params['postID']=4)?
最佳答案
这是一个可能有帮助的基本版本。首先,它将您的路径和变量转换为正则表达式。然后它依次检查每个传入的 URL。如果找到匹配项,则会将路径和变量传递给您的 url 函数。
$incomingUrl = 'posts/all/123';
$routes = ['posts/all/{postID}', 'users/all/{userID}', 'pasta/all/{pastaID}'];
// Parse your url templates into regular expressions.
$routeRegexes = [];
foreach ($routes as $route) {
$parts = [];
$partsRegex = '`(.+?){(.+?)}`';
preg_match($partsRegex, $route, $parts);
$routeRegexes[] = [
'path' => $parts[1],
'varName' => $parts[2],
'routeRegex' => "`($parts[1])(.+)`"
];
}
print_r($routeRegexes);
// Check the incoming url for a match to one of your route regexes.
$urlMatch = null;
foreach ($routeRegexes as $routeRegex) {
if (preg_match($routeRegex['routeRegex'], $incomingUrl, $urlMatch)) {
$routeRegex['varValue'] = $urlMatch['2'];
$urlMatch = $routeRegex;
break;
}
}
print_r($urlMatch);
if (!empty($urlMatch)) {
$path = $urlMatch['path'];
$variableName = $urlMatch['varName'];
$variableValue = $urlMatch['varValue'];
echo "Path: $path\n";
echo "Variable name: $variableName\n";
echo "Variable value: $variableValue\n";
// Pass the variables to your url function.
// callUrl($path, [$variableName => $variableValue]);
} else {
// Throw 404 path not found error.
}
希望这能为您指明正确的方向。
关于javascript - 大括号中的 PHP 动态 URL 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41861789/