Replace the same characters with different lines

Assuming I have a string

$str = "abc*efg*hij*"; 

and array

 $arr = array("123","456","789"); 

Now I want to replace * with $str with elements in $arr according to the positions. The first * replaced by $arr[0] , the second is replaced by $arr[1] , etc. I check the str_replace function, although it accepts arrays as parameters, but I found that this did not work. And I can’t just use

 $newstr = "abc{$arr[0]}efg{$arr[1]}hij{$arr[2]}" 

because the real $str can be a pretty long string with a lot of * . Any good ideas? Thanks.

+4
source share
2 answers

If * is your only format character, try converting * to %s (also open the existing % to %% ), and then use vsprintf() , which takes an array of values ​​as format parameters:

 $str = str_replace(array('%', '*'), array('%%', '%s'), $str); $newstr = vsprintf($str, $arr); echo $newstr; 

Output:

 abc123efg456hij789 

Please note that if you have more array elements than asterisks, additional elements at the end simply will not appear on the line. If you have more stars than array elements, vsprintf() will issue a warning and return too few false arguments.

+11
source

You can always just save this with preg_replace() and use the $limit argument, for example:

 for($i = 0; $i < count($arr); $i++) $str = preg_replace('/\*/', $arr[$i], $str, 1); 

but for practicality, @BoltClock's answer is a better choice, since it does not include a loop, but more importantly b) is not forced to use a regular expression.

+1
source

All Articles