我有一条短信说:
$text = "An Elephant is an Elephant but an Elephant is not an Elephant"
我有一个数组说:
$array = array("First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eight", "Ninth");
在文本中,您可以看到“大象”的出现次数很多。我想做的是用数组中的唯一值替换出现的Elephant,结果应该是这样的:
$result = "An Fifth is an Seventh but an First is not an Fourth"
到目前为止,我已经尝试过了:
$arr = array("First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eight", "Ninth");
$text = "an elephant is an elephant but an elephant is not an elephant";
$array = explode(" ", $text);
$new_arr = array_diff($array, array("elephant"));
$text = implode(" ".$arr[array_rand($arr)]." ", $new_arr);
echo $text;
它输出如下内容:
an First is First an First but First an First is First not First an
我怎么会这样?
An Fifth is an Seventh but an First is not an Fourth
最佳答案
这应该为您工作:
使用preg_replace_callback()
,您可以简单地使用array_rand()
始终将其替换为数组中的随机值。
<?php
$arr = array("First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eight", "Ninth");
$text = "an elephant is an elephant but an elephant is not an elephant";
echo $newText = preg_replace_callback("/\belephant\b/", function($m)use($arr){
return $arr[array_rand($arr)];
}, $text);
?>
可能的输出:
an Seventh is an Third but an First is not an Ninth
关于php - PHP用数组中的值替换子字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31805189/