gpt4 book ai didi

php - 正则表达式捕获 URL 中的第一个 slug 如果它有多个 slug/path 则不捕获

转载 作者:行者123 更新时间:2023-12-04 08:59:51 30 4
gpt4 key购买 nike

我想捕获 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 协议(protocol)。
我的正则表达式: 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,但我的正则表达式捕获了所有这些 URL。

最佳答案

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

/example\.com\/path\/([^\/]+)\/?$/
https://regex101.com/r/K75aDD/1

编辑:正如 user3783243 提到的,如果它与带有大量斜杠的路径相关,则通常更容易为您的正则表达式使用不同的分隔符,因此您不必全部转义。约定通常是使用散列 #或波浪号 ~在这些情况下。
#example\.com/path/([^/]+)/?$#

关于php - 正则表达式捕获 URL 中的第一个 slug 如果它有多个 slug/path 则不捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63615046/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com