代码之家  ›  专栏  ›  技术社区  ›  Jan Wytze

PHP preg\u replace reuse editted match in replace替换

  •  0
  • Jan Wytze  · 技术社区  · 7 年前

    我正在尝试创建一个URL匹配模式,其中可以读取路由参数。

    这就是我所拥有的:

    $routePattern = '/test/{id}/edit';
    // Can I strip the opening and closing bracket from `$0` here?
    $regexPattern = '#^' . preg_replace('#{[\w]+}#', '(?P<$0>[\w]+)', $routePattern) . '$#';
    // Matching done here...
    

    问题是,这将导致: #^test/(?P<{id}>[\w]+)/edit$# . 但我想把支架从 id . 因此,我希望得到以下结果: #^test/(?P<id>[\w]+)/edit$# .

    这怎么可能呢?这是我发现的不干净的方式:

    $routePattern = '/test/{id}/edit';
    $regexPattern = '#^' . preg_replace('#{[\w]+}#', '(?P<$0>[\w]+)', $routePattern) . '$#';
    $regexPattern = str_replace(['{', '}'], '', $regexPattern);
    // Matching done here...
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Matt S    7 年前

    使用 capturing subpattern 通过包围 \w+ 括号内:

    preg_replace('#{([\w]+)}#', '(?P<$1>[\w]+)', $routePattern)
    
        2
  •  0
  •   Alexandra    7 年前

    我可能会使用一个捕获组,并反向引用:

    ({)(.)*(})
    

    $2 而不是 $0

    $regexPattern = '#^' . preg_replace('#({)([\w]+)(})#', '(?P<$2>[\w]+)', $routePattern) . '$#';
    // Matching done here...
    

    像那样?

    这是一个很好的正则表达式资源: https://regexr.com/