str_replace与数组的意外行为

时间:2013-03-01 19:14:53

标签: php arrays str-replace

我有以下功能,使用str_replace会产生意外结果

function repo($text) {
    $search = array("0","1","2","3","4","5","6","7","8","9");
    $replace = array("z30","z31","z32","z33","z34","z35","z36","z37","z38","z99");
    $text = str_replace($search,$replace,$text);
    return $text;
}

echo repo('0');

预期答案是

z30

而我得到

zz330

我做错了什么?

2 个答案:

答案 0 :(得分:5)

你的功能就是这样。

0更改为z30,php继续循环数组,然后z30包含'3',并且3更改为z33。 因为返回'z'+'z33'+'0'= zz330。

答案 1 :(得分:1)

就像the documentation说的那样:

  

因为str_replace()从左到右替换,所以它可能会替换a   多次替换时先前插入的值。

你可能想要做这样的事情:

function repo($text){
    $search = array("0","1","2","3","4","5","6","7","8","9");
    $replace = array("z30","z31","z32","z33","z34","z35","z36","z37","z38","z99");
    $replacePairs = array_combine($search, $replace);
    return strtr($text, $replacePairs);
}