views:

215

answers:

2

I need to replace multiple instances of a certain string (question mark) with strings from an array. e.g. if the string I wish to replace appears 3 times and my array has a length of 3, the first one would be replaced by the first item in the array, the second by the second etc etc.

You may recongise it's quite similar to the way prepared statements work in mysqli.

Here's an example:

$myArray = array(
    [0] => 'yellow',
    [1] => 'green',
    [2] => 'red'
);

$myString = 'banana is ?, apple is ?, tomato is ?';

$newString = someFunction($myString,$myArray);

echo $newString;

This would then return

banana is yellow, apple is green, tomato is red

Can anyone suggest a way of doing this using PHP 5.2.

+5  A: 

why not use

$retString = vsprintf('banana is %s, apple is %s, tomato is %s', $myArray);  
return $retString;
Adam Kiss
+1 This is the best solution.
mck89
Hmm I totally forgot about sprintf (it's one of those functions i've never really used for some reason). That would actually work really well, although in my case I do need to use question marks so i'll have to do some replacing, but infact, for my particular case, that will work out fine.Accepted solution, thanks alot.
Rob
well if you're doing simple replace, you can always do something like `str_replace($str, '?', '$s');` :] Glad I helped.
Adam Kiss
It's worth noting that sprintf can strongly type your data for you.
cballou
if for some reason you have to use question marks, then replace question marks first. Something like `$str=preg_replace('/([^\\\\]|^)\?/', '%s',$str);` handles quoted question marks as well.
gnud
@Adam Kiss: beautifully elegant solution.
matt
@matt - thank you
Adam Kiss
+1  A: 

It gets a little ugly in PHP 5.2 because you have to use global variables to pass information between callbacks but it's very flexible otherwise. Use preg_replace_callback():

preg_replace_callback('!\?!', 'rep_array', $myString);

$i = 0;

function rep_array($matches) {
  global $myArray;
  return $myArray[$i++];
}

You'd have to cater for there being more ?s than array entries as well as reset the counter with each call.

Adam is right about sprintf() being somewhat cleaner but you don't always control the input string. preg_replace_callback can cater for a far wider range of circumstances.

cletus