codeigniter routing (regex)
I am trying to route a url as follows:
domain.com/param/some_controller/method/
mapped to
some_controller::method($param)
I am开发者_如何学Go not skilled with regular expressions, which i'm fairly certain are necessary, so I would really appreciate it if someone could help get me started? Or point me to a good tutorial or example?
$route['(:any)/some_controller/method/'] = "some_controller/method/$1";
if your param is a number use (:num)
instead.
in your controller
function method($my_param) {
echo 'my param is '. $my_param;
}
an RL example:
$route['(:num)/blog/entry/'] = "blog/view/$1";
class Blog extends CI_Controller {
function view($id) {
echo 'fetching blog entry no ' . $id;
}
}
your view will look like
view.php
<html>
<body>
link to <?= anchor('1/blog/entry/','my first post'); ?>
link to <?= anchor('2/blog/entry/','my second post'); ?>
</body>
</html>
This is a little messy, because there is currently no way to do this with routing without confusing things. You can try this:
$route['([^/]+)/([^/]+)/([^/]+)'] = "$2/$3/$1";
BUT what this says is that it will apply to ANY url: this will confuse regular controllers. You are better served adding some prefix to identify requests you should process with this route: for example
$route['a/([^/]+)/([^/]+)/([^/]+)'] = "$2/$3/$1";
Same effect, but Codeigniter-style:
//remember that custom routes need to go _after_ ci's default routes, as they're executed in the order you provide them
$route['default_controller'] = "welcome";
$route['404_override'] = '';
//exception 1 to your regex here
//exception 2 to your regex here
//so on...
$route['(:any)/(:any)/(:any)'] = "$2/$3/$1";
精彩评论