以下面的正则表达式匹配为例。
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);
它产生以下内容:
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
)
然而,由于最后一个匹配是可选的,它也可以匹配以下“publisher/news/1/2010-march:03-23/test_title/1”。我的问题是我希望能够匹配 (/page-[0-9]+) 如果它存在,但只匹配页码所以“publisher/news/1/2010-march:03-23/test_title/ 1/page-1" 会像这样匹配:
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
)
我尝试了以下正则表达式
'!^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]+)?$!'
这可行,但它也将匹配“publisher/news/1/2010-march:03-23/test_title/1/1”。我不知道要进行比赛,但没有在比赛中回来?是否可以在单个正则表达式中使用?