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

PHP replace sub string with the value from an array

我有一条短信说:

$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

这应该适合你:

使用 preg_replace_callback() you can then simply use 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

改编自 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);

给,你为什么不试试这个?

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