正如我之前提到的,您可以将 的值指定$search为一个数组。如果$replace是单个字符串,那么$search数组中的所有值都将替换为$replace我们的主字符串。
<?php
$sentence = "There were 60 bananas and 12 oranges in the first basket. Some children ate 2 mangoes each.";
$search = ["bananas", "mangoes"];
$replace = "apples";
$new_sentence = str_replace($search, $replace, $sentence);
// There were 60 apples and 12 oranges in the first basket. Some children ate 2 apples each.
echo $new_sentence;
?>
两者$search和$replace都可以指定为数组。在这种情况下,$search中的第一个元素将被$replace中的第一个元素替换,依此类推。换句话说,$search将被$replace相应索引处的子字符串替换。
<?php
$sentence = "There were 60 bananas and 12 oranges in the first basket. Some children ate 2 mangoes each.";
$search = ["bananas", "mangoes"];
$replace = ["apples"];
$new_sentence = str_replace($search, $replace, $sentence);
// There were 60 apples and 12 oranges in the first basket. Some children ate 2 each.
echo $new_sentence;
?>
这个例子与我们上面写的用苹果代替香蕉和芒果的例子非常相似。这次唯一的区别是现在是一个包含单个元素的数组。但是,这会导致完全不同的结果,因为mangoes现在将被空字符串替换。
如果$search和$replace数组的长度不相等怎么办?如果$search元素多于$replace,则$search中的额外元素将被空字符串替换。