I've had a go at this, and I cant see how str_replace would solve this issue.
My understanding is that the OP wants to change the keyword 'nice' to two separate values. So ... "It's a fine day in a fine way" might become "It's a good day in a glorious way."
However, passing an array of replacements to str_replace seems to throw a warning if search is a string and replacements an array. And if you pass an array of the same replacement value, it still replaces all instances with the first replacement.
Code: Select all
$phrase = "I saw a ? and a ? run off with my ?";
$insert = array('dog', 'cat', 'sausage');
$markers = array_fill(0, count($insert), '?');
echo str_replace($markers, $insert, $phrase);
produces
I saw a dog and a dog run off with my dog
I cant see a way of making str_replace make multiple replacements for the same search.
Or is there?
/*** EDIT
My code example is not really the best. It could be better achieved with vsprintf on "I saw a %s and a %s run off with my %s". But still ... it's not really a word replacement as the OP was looking for. Besides, I'd prefer to use ? instead of %s anyhow.
/*** EDIT #2
Actually ... I guess you could go ...
Code: Select all
$original = "It's a fine day in a fine way";
$working = str_replace('fine', '%s', $original, $changes);
$values = array('glorious', 'wonderful', 'marvelous', 'good', 'grand');
$ins_keys = array_rand($values, $changes);
foreach($ins_keys as $id=>$key) $inserts[$id] = $values[$key];
$result = vsprintf($working, $inserts);
echo $result;
.... though somehow it seems more trouble than it's worth;