Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

niseku's avatar

Regex to extract categories from URL

Hi guys

I have a Slug (aktuell/blog/cat1/cat2/cat3) an need a Regex to extract all category-segments (all segements after 'aktuell/blog') from this Slug. The count of cataegory-segements may vary from zero to infinity.

I have already tried several ways but it never works... My last attempt was:

 ^aktuell\/blog(?:\/(\w+))*$/g

But this Regex returns just the last segment as match... What can i do to get all categories?

Thank's

0 likes
3 replies
ohffs's avatar

Could you just use explode instead?

niseku's avatar

Unfortunately not...

I have a routing class which deals with the regex patterns (from db) and returns me the route id and all matches.

niseku's avatar
niseku
OP
Best Answer
Level 2

This Regex works, but the php Regex-Engine can't handle matches in a repeating group. Every new match overrides the previous one... So my solution is to repeat the group manually:

^aktuell\/blog(?:\/(\w+))?(?:\/(\w+))?(?:\/(\w+))?(?:\/(\w+))?(?:\/(\w+))?

Please or to participate in this conversation.