PHP用数组中的值替换子字符串

时间:2015-08-04 09:12:22

标签: php arrays string str-replace

我有一个文字说:

$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"。我想要做的是我想用数组中的唯一值替换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

3 个答案:

答案 0 :(得分:5)

在这里,为什么不尝试这个?

$arr = array("First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eight", "Ninth");
$arrlength = count($arr);
$text = "an elephant is an elephant but an elephant is not an elephant";
$array = explode(" ", $text);
for ($i=0; $i < count($array); $i++) { 
    if ($array[$i]=="elephant")
    {
        $random_key = array_rand($arr, $arrlength);
        $array[$i] = $arr[$random_key[rand(0, $arrlength-1)]];
    }
}
$text = implode(" ", $array);
echo $text;

答案 1 :(得分:3)

这应该适合你:

使用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

答案 2 :(得分:0)

适应Rizier123的答案,所以你永远不会有相同的替代品。 (注意你不需要更换比你阵列中的物品数量更多的物品)

$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){
  $item = array_rand($arr);  
  $return = $arr[$item];
  unset($arr[$item]);
  return $return;
}, $text);