Combining Codeigniter routes with regex
I've been playing around with creating an e-commerce site with Codeigniter, and am trying to do the following:
Have category names as the first parameter, e.g.
/tshirts
/shoes
following each of these, is either a filter (on the category), or the product (with category in URL for SEO)
/tshirts/filter/price/0-20
/tshirts/pink-with-blue-spots
What I’m currently doing in the routing is this:
$route['tshirts'] = 'category/index';
$route['tshirts/(filter|sort)'] = 'category/index';
$route['tshirts/(filter|sort)/:any'] = 'category/index/filter';
$route['tshirts/:any'] = 'product/index';
I want to combine the first two lines into one, as they are accessing the same controller and method.
The second line is there incase someone removes the part after /filter/
, and could possibly be combined with another route.
The last route means the second parameter is a product name, so must be passed to the product controller.
I've been playing with http://gskinner.com/RegExr/ and come up with the following, which might be close, think I just need to make the part in brackets optional (it’s picking up t开发者_JAVA百科he correct routes, except the one without any second parameter), but I'm not sure how to.
category/?(filter|sort|page)
Thanks!
Had a quick look at this today, have now combined the
$route['tshirts/(filter|sort)'] = 'category/index';
$route['tshirts/(filter|sort)/:any'] = 'category/index/filter';
into
$route['tshirts(/(filter|sort|page)(/(:any))?)?'] = "category/index/$4";
And in the index($filter = null)
method of the category controller, use $filter != null
to see whether the filter rules need to be applied.
I’m not familiar with the syntax of CodeIgniter routes. But try this:
$route['tshirts(/(filter|sort))?'] = 'category/index';
And if non-capturing groups are supported:
$route['tshirts(?:/(filter|sort))?'] = 'category/index';
精彩评论