I’m using code igniter and am trying to capture multiple url segments via the $routes array.
For example, my url will look like this:
/segment-1/segment-2/keyword/
I have been trying to use just this regexp:
$route['([\w-?]+){1,3}'] = "my/method";
but that only returns this subgroup match:
segment-1
then when i try this route:
(\/[\w-?]+){1,3}
it returns this as the subgroup match:
/keyword
so I have been explicitly putting the exact route I want to make sure I capture all the instances:
$route['([\w-?]+)'] = 'my/method/$1';
$route['([\w-?]+)/([\w-?]+)'] = 'my/method/$1/$2';
$route['([\w-?]+)/([\w-?]+)/([\w-?]+)'] = 'my/method/$1/$2/$3';
which obviously is rather verbose.
ultimately, I would like to capture all segments in one regexp.
thoughts?
It is generally impossible to have arbitrarily many capture groups in one regular expression. As you can see from your own attempts, if you repeat one capture group, you will just get the last match. However, you could solve it up to a certain number of path elements by making additional “directories” optional. Say 3 is your maximum:
You could add a few more nested
(/[\w-?]+)?at the end to allow for deeper paths. Otherwise you can fill your$routearray automatically with a loop, but that, too, will only work to a fixed depth.