Reputation: 10981
I'm testing out some regex expressions to work with subpatterns so I can aplly through PHP the defined rules for each uri segment. Some of those segments are optional, so I tried this :
preg_match('#^/(?P<controller>[\w-]+)(?:/(?P<[\w-]+)(?:/(?P<id>[\d]+)))/?$#uD', '/blog/post', $matches);
This regex matches /blog/post/1
but not blog/post
as it should, since both the second and third parameters are optional. Any clues?
Upvotes: 1
Views: 866
Reputation: 44259
Why would the second and third part be optional? There is no ?
that makes them optional. The ?
you have is only applied to the last slash. Also, you need to make sure that the third group is still optional if the second one is present. Maybe you were looking for something like this:
'#^/(?P<controller>[\w-]+)(?:/(?P<item>[\w-]+)(?:/(?P<id>[\d]+))?)?/?$#uD'
Note that in your question the second capturing group was not valid, because you had an opening <
and not group name to follow. I changed that because I figured it might have been a typo in the question.
It might greatly increase the readability of your code if you took a different approach than regex, though. How about exploding at /
. Then $result[1]
would be your controller. Then you could check if there is a $result[2]
and check that it is a valid "item" (or whatever you call it). And then you could check if there is a $result[3]
, if that is a number and use it as your id
. This approach is easily extensible to multiple parameters, and to checking for different allowable items.
Upvotes: 4