Mwthreex
Mwthreex

Reputation: 1059

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

I want to capture the first slug in the URL only if the URL has one slug, and ignore if it has more than one slug or section in the URL. For example:

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

Trailing slash and no HTTP protocol is allowed.

My regex: 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'
}

It should capture the first and second URLs I posted, but my regex captures all of them.

Upvotes: 2

Views: 1179

Answers (1)

BadHorsie
BadHorsie

Reputation: 14564

Capture everything that doesn't include a slash, and allow it only to have an optional trailing slash before the end of the string.

Regex

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

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


Edit: As user3783243 mentioned, it's generally easier to use a different delimiter for your regex if it's related to paths with lots of slashes, so you don't have to escape them all. Convention is often to use a hash # or tilde ~ in these situations.

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

Upvotes: 2

Related Questions