Php路由解析器URL的结尾

 warcraft04 发布于 2023-02-12 12:57

我为自己的php-mvc-framework编写了一个小的php url解析器,我在以下代码中需要一些帮助:

routes[] = array('method' => $method, 
                          'url' => $url, 
                          'callback' => $callback);
}

public function doRouting(){
    $reqUrl = $_SERVER['REQUEST_URI'];
    $reqMet = $_SERVER['REQUEST_METHOD'];
    foreach($this->routes as  $route) {

        // convert urls like '/users/:uid/posts/:pid' to regular expression      
        $pattern = "@^" . preg_replace('/\\\:[a-zA-Z0-9\_\-]+/', '([a-zA-Z0-9\-\_]+)', preg_quote($route['url'])) . "$@D";
        $matches = array();

        if($reqMet == $route['method'] && preg_match($pattern, $reqUrl, $matches)) {

            // remove the first match
            array_shift($matches);
            // call the callback with the matched positions as params
            return call_user_func_array($route['callback'], $matches);
        }
    }
}

$route = new Route();

$route->addRoute('GET', '/', function(){
     echo 'root';
});

 $route->addRoute('GET', '/users/', function(){
     echo 'users';
 });
 $route->addRoute('GET', '/users/:uid/posts/:pid/', function($uid, $pid){
     echo $uid.'
'.$pid; }); $route->addRoute('GET', '/users/:uid/posts/:pid/edit', function($uid, $pid){ echo 'users posts edit'; }); $route->doRouting();

我想/在URL的末尾允许一个可选项.例如,在当前的路由定义时REQUEST_URI/users/123/posts/456我想同样的结果(函数调用)时REQUEST_URI/users/123/posts/456/.

另外,/users/123/posts/456/edit调用新功能.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有