PHP str_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.
例如:
$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!
推荐答案
您可以使用的 preg_replace_callback 来执行功能的每场比赛,并返回替换字符串:
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);
样 $结果
:
欢迎到亚特兰大。我想每次达拉斯是一个随机的版本。迈阿密不应该是相同的亚特兰大每次
Welcome to Atlanta. I want Dallas to be a random version each time. Miami should not be the same Atlanta each time.
这篇关于PHP str_replace函数替换需要与阵列随机替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!