Kri*_*log 2 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);
Run Code Online (Sandbox Code Playgroud)
结果是每次出现的城市都有"数组".我需要用$ 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);
Run Code Online (Sandbox Code Playgroud)
样品$result:
欢迎来到亚特兰大 我希望达拉斯每次都是随机版.迈阿密每次都不应该是同一个亚特兰大.
你可以使用preg_replace_callback与array_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;
Run Code Online (Sandbox Code Playgroud)
这里的例子.