doubao7287 2013-05-24 19:23
浏览 25
已采纳

将网址与字母数字,短划线和下划线字符匹配?

How can I match the following function with the segment in the middle ("/(\w+)\") to allow URL characters like alphanumerics & _.- ?

if(preg_match('/^\/segment1\/(\w+)\/segment2/', '/segment1/aAbB0123.-_Z/segment2', $match)) {                       
    print_r($match);
    /*
    * Array
    (
        [0] => /segment1/s/segment2
        [1] => aAbB0123.-_Z
    )
    *
}
  • 写回答

1条回答 默认 最新

  • drhqkz3455 2013-05-24 19:45
    关注

    There's one other issue with your pattern, it's requiring a forward slash at the end, whereas your input does not have one. I wouldn't even make it optional, just leave it out altogether, you can't get more optional than that.

    Is your goal here to Validate, or to Capture that middle segment? I'm assuming capture since in your example there would be no other reason to have a sub-expression. Giving a couple exact input examples and what you actually require would be best.

    So, you have a few options.

    Super lazy:

    segment1/(.*?)/segment2
    

    One Sub-Segment, also Super lazy:

    segment1/([^/]+)/segment2
    

    Exact Requirements (Find out what you want in a URL, I'm pretty sure some of those characters you listed aren't allowed in a URL, just in the Querystring):

    segment1/([-\w&.%=#]+)/segment2
    

    Allow Multiple Segments, Lazy:

    segment1/((?:[^/]+/?)+)/segment2
    

    Allow Multiple Segments, Exact Requirements:

    segment1/((?:[-\w&.%=#]+/?)+)/segment2
    

    Depending on your settings, you may need to escape some things.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog