phparraysstringrandomstr-replace

PHP str_replace to replace need with random replacement from array?


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!


Solution

  • You can use preg_replace_callback to execute a function for each match and return the replacement string:

    $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 = preg_replace_callback('/' . preg_quote($keyword) . '/', 
      function() use ($values){ return $values[array_rand($values)]; }, $text);
    

    Sample $result:

    Welcome to Atlanta. I want Dallas to be a random version each time. Miami should not be the same Atlanta each time.