Javascript 大括号中的PHP动态URL变量

Javascript 大括号中的PHP动态URL变量,javascript,php,html,string,url,Javascript,Php,Html,String,Url,我需要检查路由是否存在,数组中的路由是字符串,路由存储在字符串数组中,例如routes[0]=“posts/all/{postID}”注意大括号和参数名。假设用户使用url“post/all/4”进入站点。如何将浏览器中输入的url与带有大括号和参数名的url进行匹配,如果数组中有一个匹配项,则调用一个函数,该函数只获取大括号中参数前面的url部分,并将大括号内的变量及其原始名称传递给该函数,该函数可以是一个数组,例如params['postID']=4?这是一个基本版本,可能会有所帮助。首先,

我需要检查路由是否存在,数组中的路由是字符串,路由存储在字符串数组中,例如routes[0]=“posts/all/{postID}”注意大括号和参数名。假设用户使用url“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.
}

希望这能为您指明正确的方向。

没问题。我想如果你点击灰色的勾号来接受答案,这会给我们双方带来一些声誉。