Codeigniter - 获取当前路线

and*_*ard 3 php codeigniter

我正在寻求帮助,以了解我的Codeigniter应用程序通过哪条路线.

在我的config/routes.php的应用程序文件夹中,我得到了一些数据库生成的路由,可能如下所示:

$route["user/:any"] = "user/profile/$1";
$route["administration/:any"] = "admin/module/$1";
Run Code Online (Sandbox Code Playgroud)


如果我例如去domain.net/user/MYUSERNAME,那么我想知道我通过路线"user /:any".
是否有可能知道它遵循哪条路线?

Ade*_*eel 7

知道路线的一种方法是使用这个:

$this->uri->segment(1);

这会给你这个网址的"用户":

domain.net/user/MYUSERNAME

通过这种方式,您可以轻松识别您所经历的路线.


and*_*ard 3

我用@Ochi的答案来想出这个。

$routes = array_reverse($this->router->routes); // All routes as specified in config/routes.php, reserved because Codeigniter matched route from last element in array to first.
foreach ($routes as $key => $val) {
$route = $key; // Current route being checked.

    // Convert wildcards to RegEx
    $key = str_replace(array(':any', ':num'), array('[^/]+', '[0-9]+'), $key);

    // Does the RegEx match?
    if (preg_match('#^'.$key.'$#', $this->uri->uri_string(), $matches)) break;
}

if ( ! $route) $route = $routes['default_route']; // If the route is blank, it can only be mathcing the default route.

echo $route; // We found our route
Run Code Online (Sandbox Code Playgroud)