tags:

views:

57

answers:

1

Hello; I have a regular expression like:

'/items\/a=(0-9)+\/b=(0-9)+/'

which matches urls like:

items/a=5/b=5, items/a=11/b=9 etc. (I hope the regex is correct, but please do not mind if it is not)

What I want to be able to do is injecting values back into this regexp so lets say I have a=99, b=99 for values and I want to work out the string items/a=99/b=99. It can be done manually with string operations but is there a way to do this using the regex pattern itself?

The reason I want to do this is I am trying to write a routing method for a front controller. Assuming I match the url /product/3 to controller = ProductController, action = display, id=3 I want to be able to create the url back using a function createUrl($controller, $action, $params) from the regex.

I hope it was clear, my English is not very good so sorry on that.

A: 

yes, you need to find out offset for each group in your expression and then insert substrings at specific offsets (starting from the end of the string)

 $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]));
 }
stereofrog
I think you meant to change his regex to `([0-9]+)` rather than `([0-9])+` in order to conform with your matching requirements.
Kevin Peno