gpt4 book ai didi

PHP str_replace 用数组中的随机替换来替换需要?

转载 作者:行者123 更新时间:2023-12-04 21:49:34 30 4
gpt4 key购买 nike

我已经研究过并且需要找到用一系列随机可能性替换需求的最佳方法。

即:

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

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

最佳答案

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

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 用数组中的随机替换来替换需要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10973958/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com