繁体   English   中英

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

[英]Regex Capture first slug in the URL don't capture if it have more that one slug/path

当 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,但我的正则表达式捕获了所有这些。

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

正则表达式

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

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


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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM