【问题标题】:Combining Codeigniter routes with regex将 Codeigniter 路由与正则表达式相结合
【发布时间】:2011-01-24 10:47:10
【问题描述】:

我一直在尝试使用 Codeigniter 创建一个电子商务网站,并且正在尝试执行以下操作:

将类别名称作为第一个参数,例如

  • /tshirts
  • /shoes

在每一个之后,要么是过滤器(在类别上),要么是产品(在 SEO 的 URL 中带有类别)

  • /tshirts/filter/price/0-20
  • /tshirts/pink-with-blue-spots

我目前在路由中做的是这样的:

$route['tshirts']                    = 'category/index';
$route['tshirts/(filter|sort)']      = 'category/index';
$route['tshirts/(filter|sort)/:any'] = 'category/index/filter';
$route['tshirts/:any']               = 'product/index';

我想将前两行合二为一,因为它们正在访问相同的控制器和方法。

第二行是因为有人删除了/filter/ 之后的部分,并且可能与另一条路线相结合。

最后一个路由表示第二个参数是产品名称,所以必须传递给产品控制器。

我一直在玩http://gskinner.com/RegExr/ 并想出了以下内容,这可能很接近,我认为我只需要将括号中的部分设为可选(它选择了正确的路线,除了没有任何第二个参数的路线),但我不知道该怎么做。

category/?(filter|sort|page)

谢谢!

【问题讨论】:

    标签: regex codeigniter routing routes


    【解决方案1】:

    今天快速浏览了一下,现在已经合并了

    $route['tshirts/(filter|sort)']      = 'category/index';
    $route['tshirts/(filter|sort)/:any'] = 'category/index/filter';
    

    进入

    $route['tshirts(/(filter|sort|page)(/(:any))?)?'] = "category/index/$4";
    

    并且在类别控制器的index($filter = null)方法中,使用$filter != null查看是否需要应用过滤规则。

    【讨论】:

      【解决方案2】:

      我不熟悉 CodeIgniter 路由的语法。但是试试这个:

      $route['tshirts(/(filter|sort))?']      = 'category/index';
      

      如果支持非捕获组:

      $route['tshirts(?:/(filter|sort))?']      = 'category/index';
      

      【讨论】:

      • 试过第一个,效果很好,谢谢。另外,我了解正在发生的事情,这是一个优点:)
      猜你喜欢
      • 2014-04-14
      • 2012-09-23
      • 1970-01-01
      • 2012-06-28
      • 2014-02-25
      • 1970-01-01
      • 2010-12-30
      • 2013-05-07
      相关资源
      最近更新 更多