【发布时间】: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)~'