我在一個路由器在PHP中匹配一個模式,如「users /:id」,路由,如「users/123」 ,返回類似「id」=> 123的東西。這是我迄今爲止所擁有的。使用正則表達式來匹配一個模式的URL,返回一個鍵陣列
function match_path($path, $pattern){
if ($path == $pattern){
return true;
}
// check for :replacements
if (strpos($pattern, ":")!== false) {
// split path & pattern into fragments
$split_path = explode('/',$path);
$split_pattern = explode('/', $pattern);
// check that they are the same length
if (count($split_path) !== count($split_pattern)){
return false;
}
// iterate over pattern
foreach ($split_pattern as $index => $fragment) {
// if fragment is wild
if (strpos($fragment, ":") == 0){
$params[substr($fragment, 1)] = $split_path[$index];
// if fragment doesn't match
} elseif ($fragment !== $split_path[$index]) {
return false;
}
// continue if pattern matches
}
// returns hash of extracted parameters
return $params;
}
return false;
}
我敢肯定,必須有一種方法,用正則表達式乾淨地做到這一點。
更好的是,很可能有一個PHP函數可以做到這一點。
我不能確定你打算用它做,但'.htaccess'甚至是可能的,這是通常用於看中的URL – Sumurai8
好像他是試圖在應用程序級別實現路由。 '.htaccess'從開發的角度來看速度更快但不夠靈活。 – acobster