我正在尝试创建一个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...
答案 0 :(得分:0)
将\w+
括在括号中以使用capturing subpattern:
preg_replace('#{([\w]+)}#', '(?P<$1>[\w]+)', $routePattern)
答案 1 :(得分:0)
我可能会使用捕获组,并进行反向引用:
({)(.)*(})
应该抓住它。然后使用$2
而不是$0
所以..
$regexPattern = '#^' . preg_replace('#({)([\w]+)(})#', '(?P<$2>[\w]+)', $routePattern) . '$#';
// Matching done here...
喜欢吗?
这是用于正则表达式的重要资源: https://regexr.com/