1

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

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

4

3 回答 3

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]+))|/.*)?$!
于 2010-03-25T11:46:50.527 回答
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]+))?$!'
于 2010-03-25T11:38:45.207 回答
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+))?

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

于 2010-03-25T11:47:33.397 回答