我有一个正则表达式:
/items\/a=(0-9)+\/b=(0-9)+/
匹配网址:
items/a=5/b=5,
items/a=11/b=9
我希望正则表达式是正确的,但如果不是,请不要介意。
我希望能够做的是将值注入此正则表达式中,所以假设我有值a=99, b=99
,我想计算出字符串items/a=99/b=99
。它可以通过字符串操作手动完成,但有没有办法使用正则表达式模式本身?
我想这样做的原因是我正在尝试为前端控制器编写路由方法。假设我匹配网址
/product/3
到controller = ProductController
,action = display
,id=3
。我希望能够使用正则表达式中的函数createUrl($controller, $action, $params)
创建回传网址。
我希望很清楚,我的英语不是很好,很遗憾。
答案 0 :(得分:0)
是的,您需要找出表达式中每个组的偏移量,然后在特定偏移处插入子字符串(从字符串末尾开始)
$re = '/items\/a=([0-9])+\/b=([0-9])+/';
$str = 'items/a=5/b=6';
$replacements = array(1 => 123, 2 => 456);
preg_match($re, $str, $matches, PREG_OFFSET_CAPTURE);
for($i = count($matches) - 1; $i > 0; $i--) {
$p = $matches[$i];
$str = substr_replace($str, $replacements[$i], $p[1], strlen($p[0]));
}