I need URL pattern for my router which would match with:
/page_name.html
/page_name.html/1
/page_name.html/2
....
/page_name.html/999
And preg_match() must put page_name into matches[1] and digit after slash into matches[2] (or empty string, index [2] must always be present!).
I need this to not match my patern:
/page_name.html/
/page_name.html131
I wrote this:
^\/([\w\-]+)\.html[\/]?([\d]{1,3})?$/
But it mathces URLs like /page_name.html123 and doesn't put anything into matches[2] if there is no digit.
You can use this regex:
preg_match('~^/([\w-]+)\.html(?|/(\d{1,3})|())$~', $matches, $input);
(?|...)
- Subpatterns declared within each alternative of this construct will start over from the same index. This is to make sure to always populate $matches[2]
with something, even an empty string.