PHP str_replace 没有正确地将数字替换为字符串

PHP str_replace not correctly replacing number to string

谁能解释一下为什么 php 函数 str_replace 不能正确地将数字替换为字符串?

$number      =   [1,5,10,15];
$text        =   ["one", "five", "ten", "fifteen"];

$replaced_1  =   str_replace($number, $text, 1); 
$replaced_5  =   str_replace($number, $text, 5); 
$replaced_10  =   str_replace($number, $text, 10);
$replaced_15  =   str_replace($number, $text, 15);

echo $replaced_1."<br>"; // one
echo $replaced_5."<br>"; // five
echo $replaced_10."<br>"; // one0
echo $replaced_15; // onefive

带引号的相同结果:$number = ["1","5","10","15"]

Str_replace() 函数用 string.

中的一些字符替换一些其他字符

你真的必须和 str_replace 一起工作吗?否则就用数组来做:

$numbers = [
    1 => "one",
    15 => "fifteen",
];

echo $numbers[15];

documentation中所写:

If search or replace are arrays, their elements are processed first to last.

这意味着:输入 10 的第一个替换将 1 替换为 one,返回 one0。第一个数组 $number 中没有更多内容可以将此结果与任何内容相匹配

我可能会选择 Maik Lowrey's answer, however strtr 就是为此而生的。使用 str_replace 时,1 以及 1015 中的 1 将被替换。但是 strtr:

The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.

$replaced_1  =  strtr(1, array_combine($number, $text)); 
$replaced_5  =  strtr(5, array_combine($number, $text)); 
$replaced_10 =  strtr(10, array_combine($number, $text));
$replaced_15 =  strtr(15, array_combine($number, $text));