I've researched and need to find the best way to replace a need with an array of possibilities randomly.
ie:
$text = "Welcome to [city]. I want [city] to be a random version each time. [city] should not be the same [city] each time.";
$keyword = "[city]";
$values = array("Orlando", "Dallas", "Atlanta", "Detroit", "Tampa", "Miami");
$result = str_replace("[$keyword]", $values, $text);
The result is every occurrence has "Array" for city. I need to replace all of the city occurrences with a random from $values. I want to do this the cleanest way possible. My solution so far is terrible (recursive). What is the best solution for this? Thank you!
You're replacing a text using
$values
which is an array, so the result is just the word "Array". The replacement should be a string.You can use
array_rand()
to pick random entries from your array.The result is something like this:
If you want the city to be random each line, check @PaulP.R.O's answer.
You could use
preg_replace_callback
witharray_rand
Example here.
Here's another idea
And some output:
try this http://codepad.org/qp7XYHe4
You can use preg_replace_callback to execute a function for each match and return the replacement string:
Sample
$result
: