Reputation: 916
I am doing something like this to prepare a dynamic regex.
$mapping = "asa/user/{u}/d/{d}/{f}"; //line 1
$mapper = preg_replace('/\{.*?\}/m','(\w+)',str_replace('/','#',$mapping)); //line 2
preg_match("/".$mapper."/",str_replace('/','#',$input),$arr);
print_r($arr);
which give output like this for $input = /asa/user/ZZA/d/asasa/gh
Array ( [0] => asa#user#ZZA#d#asasa#gh [1] => ZZA [2] => asasa [3] => gh )
What I want is to get something like this.
Array ( [u] => ZZA [d] => asasa [f] => gh )
I know I can do this with using ?P, so trying this
$mapper = preg_replace('/\{.*?\}/m','(?P<name>\w+)',str_replace('/','#',$mapping));
Which obviously would not work as it will use same index name for all params,what i need to do is replace name with u,d,f dynamically. i can do this with explode i believe, then traversing the array and replace one by one. But is there any better solution to do this type of operation?
At line 2 can read value between braces and then use it as index to replace with?
Upvotes: 0
Views: 65
Reputation: 48751
At line 2 can read value between braces and then use it as index to replace with?
Yes, by capturing groups () and backrefrences $n.
You should change the second line to:
$mapper = preg_replace('/\{(.*?)\}/m','(?P<$1>\w+)', str_replace('/','#',$mapping));
Which results in:
Array
(
[0] => asa#user#ZZA#d#asasa#gh
[u] => ZZA
[1] => ZZA
[d] => asasa
[2] => asasa
[f] => gh
[3] => gh
)
Upvotes: 1