Reputation: 7337
Currently, I have a simple router class that takes URIs and attempts to match them to the incoming request URI. A simple example of a route it might try to match to the request URI would be:
/user/([0-9]+)
So, this would match a request URI of "user/1".
Now I'm trying to match optional parameters. This works:
/user([/0-9]?)
However, it seems like this would allow any number of slashes in the segment. How can I force the optional segment to be preceded by one slash and then numbers?
Upvotes: 3
Views: 1810
Reputation: 39197
Try the following regular expression:
/user(/[0-9]+)?
It will match "/user" followed by "/" plus one or more digits or "/user" alone. If you want to group the digits only you can enclose it in a non-capturing group:
/user(?:/([0-9]+))?
You can enclose it in ^
and $
in the call to preg_match
:
preg_match( "/^\/user(?:\/([0-9]+))?$/", "/user/1234", $m);
print_r($m);
Upvotes: 3