Multiple replace (probably preg_replace) of same s

2020-03-30 09:45发布

问题:

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.

回答1:

why not use

$retString = vsprintf('banana is %s, apple is %s, tomato is %s', $myArray);  
return $retString;


回答2:

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.