That wont work. What your code will do, is replace all occurrences of object with the 1 value chosen at random from the array. What your code will give, is something similar to "I love bacon, Can't get enough of bacon, and am addicted to bacon".
What you need, is a recursive solution. Recursion is the answer here, especially when you can have an infinite number of 'object' string matches. Here's a function I made right now (tested):

function replace_object($string,$array,$count){
// Find the next occurrence of 'object'
$pos = strpos($string, 'object');
// If there was an occurrence
if($pos !== FALSE){
// Replace that string using a substr before the o in object, and after the t in object
$string = substr($string,0,$pos).$array[rand(0,$count)].substr($string,($pos+6));
// Recur function to check for more occurrences of object
return replace_object($string,$array,$count);
}
else{
// No more object strings, return the string as it is, killing the recursion
return $string;
}
}
$array = array("narwhal","bacon","rage","fffffffuuuuuuuuuuu");
// Work out length of array, -1 for using as index
$count = count($array)-1;
$string = "I love object, Can't get enough of object, and am addicted to object";
echo replace_object($string,$array,$count);

Inigoesdr

09-14-2011, 08:37 PM

Here is an alternative using preg_replace_callback() (http://php.net/preg_replace_callback), just becase :) :