preg_match to match an optional string, but not match all of the string
- by buggedcom
Take for example the following regex match.
preg_match('!^publisher/([A-Za-z0-9\-\_]+)/([0-9]+)/([0-9]{4})-(january|february|march|april|may|june|july|august|september|october|november|december):([0-9]{1,2})-([0-9]{1,2})/([A-Za-z0-9\-\_]+)/([0-9]+)(/page-[0-9]+)?$!', 'publisher/news/1/2010-march:03-23/test_title/1/page-1', $matches);
print_r($matches);
It produces the following:
Array
(
[0] => publisher/news/1/2010-march:03-23/test_title/1/page-1
[1] => news
[2] => 1
[3] => 2010
[4] => march
[5] => 03
[6] => 23
[7] => test_title
[8] => 1
[9] => /page-1
)
However as the last match is optional it can also work with matching the following "publisher/news/1/2010-march:03-23/test_title/1". My problem is that I want to be able to match (/page-[0-9]+) if it exists, but match only the page number so "publisher/news/1/2010-march:03-23/test_title/1/page-1" would match like so:
Array
(
[0] => publisher/news/1/2010-march:03-23/test_title/1/page-1
[1] => news
[2] => 1
[3] => 2010
[4] => march
[5] => 03
[6] => 23
[7] => test_title
[8] => 1
[9] => 1
)
I've tried the following regex
'!^publisher/([A-Za-z0-9\-\_]+)/([0-9]+)/([0-9]{4})-(january|february|march|april|may|june|july|august|september|october|november|december):([0-9]{1,2})-([0-9]{1,2})/([A-Za-z0-9\-\_]+)/([0-9]+)/?p?a?g?e?-?([0-9]+)?$!'
This works, however it will also match "publisher/news/1/2010-march:03-23/test_title/1/1". I have no idea to perform a match but not have it come back in the matches? Is it possible in a single regex?