0

我有以下功能,使用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

我究竟做错了什么?

4

2 回答 2

5

您的功能以这种方式工作。

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

于 2013-03-01T19:19:27.317 回答
1

就像文档说的那样:

因为 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");
    $replacePairs = array_combine($search, $replace);
    return strtr($text, $replacePairs);
}
于 2013-03-01T19:33:08.733 回答