【问题标题】:RegEx for capturing ID numbers in URLs用于捕获 URL 中的 ID 号的正则表达式
【发布时间】:2019-05-16 15:27:12
【问题描述】:

我想用preg_match 捕获 URL 中的 ID。

正则表达式:

/news.[a-z0-9A-Z_ -]*.?(\d+).?(?:page)?.?([0-9]+)?\.html

我想捕获 (\d+) 的 url 对吗?

网址

http://localhost/news/content-287.html

电流输出

==> preg_match 抓住这个:

Array:
  0 => string '/news/content-287.html' (length=22)
  1 => string '7' (length=1)

我该如何解决这个问题?

编辑:

理想情况下,我想要一个可以这样的网址:

/news/title-is/page=2.html 并获取标题id和页码...

:D 谢谢艾​​玛

【问题讨论】:

    标签: php html regex preg-match regex-group


    【解决方案1】:

    您可能想简化您的表达方式。例如,在这里我们可以简单地使用捕获组来定位 URL 中所需的 ID。也许,这个表达式就足够了:

    \/news\/([a-z-]+)([0-9]+)\.html
    

    如果需要,您还可以添加/减少其边界。例如,您可以添加任何其他字符,这些字符可能位于该组中的 ID ([a-z-]+) 之前,然后您的表达式变为:

    \/news\/([a-z-\/=]+)([0-9]+)\.html
    

    正则表达式

    如果这不是您想要的表达式,您可以在regex101.com 中修改/更改您的表达式。

    正则表达式电路

    您还可以在jex.im 中可视化您的表达式:

    代码

    $pattern = '/\/news\/([a-z-\/=\?]+)([0-9]+)\.html/is';
    $subject = 'http://localhost/news/content/title-id/id=287.html';
    preg_match_all($pattern, $subject, $matches);
    
    var_dump($matches);
    

    输出

    array(3) {
      [0]=>
      array(1) {
        [0]=>
        string(34) "/news/content/title-id/id=287.html"
      }
      [1]=>
      array(1) {
        [0]=>
        string(20) "content/title-id/id="
      }
      [2]=>
      array(1) {
        [0]=>
        string(3) "287"
      }
    }
    

    【讨论】:

    • 您好,感谢您的回答!如果我的 url 有时是 /news/title-id/page=2.html 有时没有 /page 扩展怎么办,因为我也需要捕获页面的 id...
    • 所以 preg_match 不仅能捕捉到 () 上的内容吗?
    • 已编辑:D 对不起,我是新来的,试图了解它是如何工作的 ^^
    猜你喜欢
    • 2022-01-12
    • 2012-03-20
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    相关资源
    最近更新 更多