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
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.
why not use
$retString = vsprintf('banana is %s, apple is %s, tomato is %s', $myArray);
return $retString;