如果:
- 随机选择的四个城市占位符不应在您的 3 句字符串中重复,并且
- 你不介意改变输入数组和
- 您将始终有足够的值来容纳所有占位符,然后:
您可以将数组作为引用变量传递到自定义函数范围。这意味着当您通过 访问和删除值时array_pop()
,不可能两次遇到同一个城市。shuffle()
在执行替换之前,您只需要输入一次数组。
代码:(演示)
$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 = ["Orlando", "Dallas", "Atlanta", "Detroit", "Tampa", "Miami"];
shuffle($values);
echo preg_replace_callback(
'/' . preg_quote($keyword) . '/',
function() use(&$values) { return array_pop($values); },
$text
);
潜在产出:
Welcome to Detroit. I want Tampa to be a random version each time. Dallas should not be the same Orlando each time.
或者
Welcome to Orlando. I want Miami to be a random version each time. Atlanta should not be the same Detroit each time.
或者
Welcome to Atlanta. I want Tampa to be a random version each time. Orlando should not be the same Dallas each time.
等等