Question

I'm trying to get grouped matches from the following URI:

route: "/user/{user}/{action}"
input: "/user/someone/news"

What's the appropriate regex for this? I've been searching myself sour for the past couple of hours...

I've tried something like this, but no result :(

~\/app\/user\/(?P<user>[.*]+)\/(?P<action>[.*]+)~

I get the groups back in the matches array, but no results based on the input inside the groups.

Desired output:

Array
(
    [0] => Array
        (
            [0] => "someone"
        )

    [user] => Array
        (
            [0] => "someone"
        )

    [1] => Array
        (
            [0] => "news"
        )

    [action] => Array
        (
            [0] => "news"
        )
)

To clarify with an example:

My controller has the following route: /app/user/{username}/{action} The request URI from the browser is: /app/user/john/news

How do I match that request URI against that route using a regex patter while catching the variables between the brackets?

Was it helpful?

Solution

/user/(?P<user>[^/]+)/(?P<action>[^/]+)

http://regex101.com/r/gL1aS2

Just to explain a couple problems with your original regex:

  • [.*]+ means a positive number of occurrences of a dot and an asterisk only, example: *.*.* or . or ......; [^/]+ describes a positive number of any characters but slashes.
  • No need to escape slashes, as they're not special characters when you're using ~ as delimiters.
  • Your regex also required /app at the beginning, which wasn't present in your string.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top