views:

36

answers:

2

Assuming I have a string

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

and an array

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

Now I want to replace the *s in $str with the elements in $arr according to the positions.The first * replaced with $arr[0],the second replaced with $arr[1] etc.I check the function str_replace,though it accepts arrays as parameters but I found it did not work.And I cannot just use

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

because the real $str may be quite a long string with lots of *.Any good ideas?Thanks.

+4  A: 

If * is your only format character, try converting * to %s (also escape existing % to %%), and then using vsprintf(), which takes an array of values to pass in as format parameters:

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

Output:

abc123efg456hij789

Note that if you have more array elements than asterisks, the extra elements at the end simply won't appear in the string. If you have more asterisks than array elements, vsprintf() will emit a too-few-arguments warning and return false.

BoltClock
Really nice one!Thanks
SpawnCxy
@SpawnCxy: if you liked it and worked for you, mark it as correct answer. :)
Shree
@Shree: With a 92% accept rate, I'm sure he knows :D There is, however, some waiting time after a question is asked before an answer can be accepted. (It should be over by now, I believe it's 15 minutes.)
BoltClock
+1, really nice and another +1 for thinking out of the box.
codaddict
@Shree,thanks for reminding me of that.
SpawnCxy
+1  A: 

You could always just keep it simple with preg_replace() and make use of the $limit argument, like so:

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

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

mway
Good solution.I'm just planning to explode it then combine the pieces,which is obviously not a good idea:)
SpawnCxy