PHP preg_match_all命名组问题

Har*_*old 1 php regex preg-match-all regex-group

我正在尝试从以下URI获取分组匹配:

route: "/user/{user}/{action}"
input: "/user/someone/news"
Run Code Online (Sandbox Code Playgroud)

什么是适当的正则表达式?在过去的几个小时里,我一直在寻找自己的酸...

我尝试过类似的东西,但没有结果:(

~\/app\/user\/(?P<user>[.*]+)\/(?P<action>[.*]+)~
Run Code Online (Sandbox Code Playgroud)

我在匹配数组中返回组,但没有基于组内输入的结果.

期望的输出:

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

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

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

    [action] => Array
        (
            [0] => "news"
        )
)
Run Code Online (Sandbox Code Playgroud)

通过一个例子澄清:

我的控制器有以下路由:/app/user/{username}/{action} 来自浏览器的请求URI是:/app/user/john/news

在捕获括号之间的变量时,如何使用正则表达式模式将该请求URI与该路由匹配?

Bug*_*ugs 5

/user/(?P<user>[^/]+)/(?P<action>[^/]+)
Run Code Online (Sandbox Code Playgroud)

http://regex101.com/r/gL1aS2

只是为了解释原始正则表达式的几个问题:

  • [.*]+表示仅出现点的正数和星号,例如:*.*.*.......; [^/]+描述任意字符的正数但是斜线.
  • 无需转义斜杠,因为当您使用~分隔符时它们不是特殊字符.
  • 您的正则表达式在开头也需要/ app,这在您的字符串中不存在.

  • 就是这个; 但是,我会使用`[^ ​​/] +`而不是`.+`(尽管两者都有效).另外,应该注意的是,由于OP使用`~`作为分隔符,所以正斜杠没有被转义. (3认同)