【问题标题】:url parse - route not foundurl 解析 - 找不到路由
【发布时间】:2011-10-09 16:15:53
【问题描述】:

我设计了一个网站,它运行良好,但最近我出于 SEO 目的修改了链接。我刚刚用- 替换了_。现在我收到一条找不到路线的错误。

这是匹配数组

$routes = array(
    array('url' => '/^products\/(?P<cat>\w+)$/', 'controller' => 'products', 'view' => 'products_list')
);

链接是这样的

http://localhost/product/sample-page

当我删除 - 或将其替换为 _ 时,它可以工作。

【问题讨论】:

  • 我打赌\w 不匹配“-”。
  • \w 用于匹配数字、单词字符(字母、数字和下划线)和空格(空格、制表符和换行符)。
  • @JeremySpouken AFAIK, \w 匹配空格、制表符或换行符。
  • 抱歉生锈了一点,必须与\s匹配才能做到这一点。

标签: php parsing url routes


【解决方案1】:

将您的正则表达式从匹配字母、数字和下划线的速记字符类 \w 更改为更明确的字符类以匹配大小写字母、数字、_-

$routes = array(
    array('url' => '/^products\/(?P<cat>[A-Za-z0-9_-]+)$/', 'controller' => 'products', 'view' => 'products_list')
);

【讨论】:

    【解决方案2】:

    您可以在这里查看示例:

    http://rubular.com/r/czUkSgbYjs

    你可以玩不同的正则表达式。

    【讨论】:

      【解决方案3】:

      您也可以将 \w 留在其中,但要明确添加 - 即

      $routes = array(
      array('url' => '/^products\/(?P<cat>[\w\-]+)$/', 'controller' => 'products', 'view' => 'products_list')
      

      );

      【讨论】:

        【解决方案4】:

        嗨,朋友们,我找到了另一种解析 url 的方法。使用它,您可以在网址末尾添加“.html”,以便搜索引擎友好。

        .htaccess 文件

        RewriteEngine On
        
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-l
        
        RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
        

        url解析代码

        $url = isset($_GET['url']) ? $_GET['url'] : null;
            $url = str_replace(".html", "", $url);
            $url = str_replace("-", "_", $url);
                //you could use rtrim(); but I had some trouble when the url had the "t" as the ending character.
            //$url = rtrim($url, '.html');
            $url = explode('/', $url);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-07-23
          • 1970-01-01
          • 1970-01-01
          • 2011-02-13
          • 2018-01-20
          • 2019-02-22
          • 1970-01-01
          • 2020-04-04
          相关资源
          最近更新 更多