str_replace 函数如何工作?

How does the str_replace function work?

我正在尝试了解 str_replace 函数。

代码:

$a = array(1,8,7,5);
$b = array(3,7,11,6);
$str = '879';
$c = str_replace($a, $b , $str);
echo $c;

输出:

11119

我不明白输出。谁能解释一下 str_replace 函数是如何工作的?

很简单,你有 879 :

  1. 8 => 7

所以你现在 779

  1. 7 => 11

现在你有 11119

您没有为 9 或 11 提供任何替代品,因此您返回的号码是 11119

str_replace 替换提供的数组 $a$b 中的一对值。 并按顺序进行,所以 str_replace($a, $b , $str) 表示:

replace 1 to 3,
then replace 8 to 7,
then replace 7 to 11
and finally replace 5 to 6.

所以,让我们开始吧:

  • 输入879,将1替换为3,输出879
  • 输入879,将8替换为7,输出779
  • 输入779,将7替换为11,输出11119
  • 输入11119,将5替换为6,输出11119