【问题标题】:PHP custom URL routingPHP 自定义 URL 路由
【发布时间】:2013-12-19 15:03:18
【问题描述】:

我正在开发一个自定义 PHP URL 路由类,但我需要一些关于正则表达式的帮助。 我希望用户添加这样的路线:

$router->addRoute('users/:id', 'users/view/');

添加路由后,脚本需要检查请求的 URL 是否与定义的格式 (users/:id) 匹配并调用用户控制器的视图方法。它还需要将 id 作为参数传递给视图方法。

我的 addRoute 方法如下所示:

public function addRoute($url, $target)
{
    $this->routes[] = ['url' => $url, 'target' => $target];
}

处理路由的方法如下所示:

public function routes()
{
    foreach($this->routes as  $route) {

        $pattern = $route['url'];

        // Check if the route url contains :id
        if (strpos($route['url'], ':id'))
        {
            // Build the pattern
            $pattern = str_replace(':id','(\d+)', $pattern);
        }

        echo $pattern . '<br />' . $this->_url;

        if (preg_match_all('~' . $pattern . '~u', $this->_url, $matches))
        {
            $this->url_parts = explode('/', $route['target']);
            $this->_params = $matches;
        }
    }
}

当前脚本循环遍历路由并检查 url 是否包含:id。如果是这样,它将被(\d+) 替换。

然后脚本会检查请求的 url 是否与模式匹配并设置一些变量。

到目前为止一切正常,但经过一些测试,匹配 url 出现了一些问题。

我希望脚本只允许/users/:id 格式的网址,但是当我调用以下网址时,它将传递给/users/1/test

如何防止脚本允许这个 url,只让它匹配定义的格式?

【问题讨论】:

    标签: php regex url router


    【解决方案1】:

    尝试以下方法:

    $router->addRoute('users/(\d+)$', 'users/view/');
    

    【讨论】:

      【解决方案2】:

      我自己解决了这个问题。 我必须在表达式之前添加 ^ 并在其后添加 +$。 使函数看起来像这样:

      private function routes()
      {
          // Loop through the routes
          foreach($this->routes as  $route) 
          {
              // Set the pattern to the matching url
              $pattern = $route['url'];
      
              // Check if the pattern contains :id
              if (strpos($route['url'], ':id'))
              {
                  // Build the pattern
                  $pattern = str_replace(':id','([0-9]+)', $pattern);
              }
      
              // Check if the requested url matches the pattern
              if (preg_match_all('~^' . $pattern . '+$~', $this->_url, $matches))
              {
                  // If so, set the url_parts var
                  $this->url_parts = explode('/', $route['target']);
      
                  // Remove the first index of the matches array
                  array_shift($matches);
      
                  // Set the params var
                  $this->_params = $matches;
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-10
        • 1970-01-01
        • 2011-05-18
        • 1970-01-01
        • 1970-01-01
        • 2016-01-09
        相关资源
        最近更新 更多