【问题标题】:Regex Capture first slug in the URL don't capture if it have more that one slug/path正则表达式捕获 URL 中的第一个 slug 如果它有多个 slug/path 则不捕获
【发布时间】:2020-08-27 11:29:10
【问题描述】:

我想在 URL 有一个 slug 时捕获 URL 中的第一个 slug,如果它在 URL 中有多个 slug 或部分,则忽略它。例如:

https://example.com/path/some-slug-with-numbers-int ✅

example.com/path/some-slug-with-numbers-int/ ✅

example.com/path/some-slug-with-numbers-int/external/slug ❌ // ignore and don't capture

尾随斜杠,不允许使用 HTTP 协议。

我的正则表达式:https://regex101.com/r/0JYHMM/1/


preg_match('/example\.com\/path\/(.*?)(\/|$)(?!\w)/', $input, $match);

if (!empty($match)) {
    $slug = $match[1];
    // $slug == 'some-slug-with-numbers-int'
}

它应该会捕获我发布的第一个和第二个 URL,但我的正则表达式会捕获所有这些。

【问题讨论】:

  • 与当前问题无关,但您可以将分隔符更改为未使用的字符,以避免在正则表达式中转义该字符的每次使用。例如preg_match('~example\.com/path/(.*?)(/|$)(?!\w)~'

标签: php regex


【解决方案1】:

捕获不包含斜杠的所有内容,并只允许它在字符串结尾之前有一个可选的尾随斜杠。

正则表达式

/example\.com\/path\/([^\/]+)\/?$/

https://regex101.com/r/K75aDD/1


编辑:正如 user3783243 提到的,如果正则表达式与包含大量斜杠的路径相关,则通常更容易为您的正则表达式使用不同的分隔符,因此您不必全部转义。在这些情况下,惯例通常是使用哈希 # 或波浪号 ~

#example\.com/path/([^/]+)/?$#

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-04
    • 2012-12-02
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多