PHP str_replace函数替换需要与阵列随机替换?(PHP str_replace to r

2019-07-29 20:28发布

我已经研究并需要找到替换的可能性的阵列随机需求的最佳途径。

即:

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

其结果是每一次出现了“阵列”的城市。 我需要从$值的随机替换所有城市出现。 我想这样做可能最彻底的方法。 我的解决方法到目前为止是可怕的(递归)。 什么是我们的最佳解决方案? 谢谢!

Answer 1:

您可以使用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

欢迎到亚特兰大。 我想每一次达拉斯是一个随机的版本。 热火不应该是每次都一样亚特兰大。



Answer 2:

你可以使用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;

例如这里 。



Answer 3:

这里的另一个想法

$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.


Answer 4:

试试这个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);


Answer 5:

您要更换使用文本$values是一个数组,所以结果只是单词“阵列”。 更换应该是一个字符串。

您可以使用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.RO的答案。



文章来源: PHP str_replace to replace need with random replacement from array?