preg_match匹配可选字符串,但不匹配所有字符串

时间:2010-03-25 11:32:58

标签: php preg-replace optional

以下面的正则表达式匹配为例。

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”。我不知道进行比赛但没有在比赛中回来?是否可以在单个正则表达式中使用?

3 个答案:

答案 0 :(得分:2)

绝对不匹配publisher/news/1/2010-march:03-23/test_title/1/whatever

!^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/whatever但忽略/whatever

!^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]+))|/.*)?$!

答案 1 :(得分:0)

也许是这样的:

'!^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]+))?$!'

答案 2 :(得分:0)

这是正在寻找的正则表达式:

^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-(\d+))?

您可以在regexbuddy中测试它。如果未设置“page-1”,则将var 9留空,否则将设置它。