doudu2515
2016-02-01 18:56
浏览 26
已采纳

如何编写这样的url模式?

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.

图片转代码服务由CSDN问答提供 功能建议

我需要路由器的URL模式,它符合:

 < 代码> /page_name.html
/page_name.html/1
/page_name.html/2
 .... \ N / page_name.html / 999 
   
 
  

并且preg_match()必须将page_name放入匹配[1]和斜线后匹配[2](或空字符串,索引[2]必须始终存在!)。

我需要这个与我的模式不匹配:

  /page_name.html/
/page_name.html131
   
 
 < 我写了这个: 
 
 
  ^ \ /([\ w \  - ] +)\。html [\ /]?([\ d] {1,3}  )?$ / 
   
 
 

但它会计算像/page_name.html123这样的网址,并且如果没有数字,则不会将任何内容放入匹配[2]。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douwan7382 2016-02-01 19:02
    已采纳

    You can use this regex:

    preg_match('~^/([\w-]+)\.html(?|/(\d{1,3})|())$~', $matches, $input);
    

    RegEx Demo

    • (?|...) - 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.
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题