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.

  • 写回答

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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制