Search code examples
phpregexpreg-match

How to match all keywords after slash using preg_match and Regex?


here are my possible matching cases

/aaa
/aaa/
/aaa/bbb
/aaa/bbb/
/aaa/bbb/ccc
/aaa/bbb/ccc/

I'm trying to catch aaa, bbb and ccc if available

I know or sure aaa is there, so the regex can be /(aaa)/([^/]*)...

I tried a few other scenarios to catch the rest of the words after slash, non-greedy /([^/]+), /([^/].+?), (/[^/].+?), (?:/(.*)) but they don't match all cases.

Any ideas?

One can test here enter link description here


Solution

  • You can use this regex with all optional matches after first match:

    ~^/([^/]+)(?:/([^/]+)(?:/([^/]+))?)?/?$~m
    

    RegEx Demo

    RegEx Breakup:

    • ^/ - Match / at start
    • ( - Start captured group #1
      • [^/]+ - Match h1 or more non-slash characters
    • ) - End captured group #1
    • (?: - Start non-capturing group #1
      • / - Match a literal slash
      • ( - Start captured group #2
        • [^/]+ - Match 1 or more non-slash characters
      • ) - End captured group #2
      • (?: - Start non-capturing group #2
        • / - Match literal /
        • ( - Start captured group #3
          • [^/]+ - Match 1 or more non-slash characters
        • ) - End captured group #3
      • )? - End non-capturing group #2 (optional match)
    • )? - End non-capturing group #1 (optional match)
    • /? - Match optional trailing / $ - End of input

    EDIT: If you want to match all the components separated by / then you can use:

    ~(?:^|\G)/([^/\n]+)~m
    

    RegEx Demo 2