PHP str_replace需要从数组中随机替换吗?

时间:2012-06-11 02:22:47

标签: php arrays string random str-replace

我已经研究并需要找到一种随机替换需求的最佳方法。

即:

$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);

结果是每次出现的城市都有“数组”。我需要用$ values中的随机替换所有城市事件。我想以最干净的方式做到这一点。到目前为止,我的解决方案很糟糕(递归)。什么是最好的解决方案?谢谢!

5 个答案:

答案 0 :(得分:7)

您可以使用preg_replace_callback为每个匹配执行一个函数并返回替换字符串:

$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);

示例$result

  

欢迎来到亚特兰大。我希望达拉斯每次都是随机版。迈阿密每次都不应该是同一个亚特兰大。

答案 1 :(得分:5)

您可以将preg_replace_callbackarray_rand

一起使用
<?php
$text = "Welcome to [city]. I want [city] to be a random version each time. [city] should not be the same [city] each time.";

$values = array("Orlando", "Dallas", "Atlanta", "Detroit", "Tampa", "Miami");

$result = preg_replace_callback("/\[city\]/", function($matches) use ($values) { return $values[array_rand($values)]; }, $text);

echo $result;

示例here

答案 2 :(得分:1)

这是另一个想法

$text = "Welcome to [city]. I want [city] to be a random version each time. [city] should not be the same [city] each time.";

$pattern = "/\[city\]/";
$values = array("Orlando", "Dallas", "Atlanta", "Detroit", "Tampa", "Miami");

while(preg_match($pattern, $text)) {
        $text = preg_replace($pattern, $values[array_rand($values)], $text, 1);
}

echo $text;

还有一些输出:

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

答案 3 :(得分:0)

您正在使用$values替换文本,这是一个数组,因此结果只是单词“Array”。替换应该是一个字符串。

您可以使用array_rand()从数组中选择随机条目。

$result = str_replace($keyword, $values[array_rand($values)], $text);

结果是这样的:

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

如果您希望城市随机每行,请查看@ PaulP.R.O的答案。

答案 4 :(得分:0)

试试这个http://codepad.org/qp7XYHe4

<?
$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");

echo $result = str_replace($keyword, shuffle($values)?current($values):$values[0], $text);