I have a string lets say this :
$string="Hi! [num:0] with [num:1]";
and an array like this :
$array[0]=array('name'=>"na","id"=>22);
$array[1]=array('name'=>"nam","id"=>19);
Now when i try to replace this string with using preg_replace() like this:
$string=preg_replace('#\!\s+\[num:(\d+)\]#ie','.$array[\1]["name"]',$string);
What i am trying to do this in the replace is that search for the pattern [num:x] and then replace it by the name in corresponding array of the key ‘x’
It works perfect for the first match but doesn’t works for the second one at all. That means after this the output i get is :
$string="Hi! na with [num:1]";
While what i want should be :
$string="Hi! na with nam";
What change should i make in this ?
The regex you mentioned will only match the first, as it check the exclamation symbol.
Remove the ‘!’ so that it will replace all.
Note : But it won’t remove the ‘!’ from the string. Also checking \s+ is not a good idea, because the regex will break if a placeholder in the string doesn’t contain a space before.