为什么带有多个数组的php str_replace会给出错误的结果,但for循环会给出正确的结果吗?

时间:2013-05-28 22:38:00

标签: php str-replace

我正在尝试替换字符串中的字符(数字和字母)。当我尝试“php”方式时,它会给某些字符带来错误的结果。为什么呢?

PHP-WAY:

$find = array( "0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f" );
$replace = array( "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p" );
$haystack = "a5c9a06bfacf5f12cf01ab3f202f6c78"

//This incorrectly returns: kpmjkkglpkmppplmmpklklnpmkmpgmhi
echo str_replace( $find, $replace, $haystack );

LOOP WAY:

$find = array( "0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f" );
$replace = array( "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p" );
$haystack = "a5c9a06bfacf5f12cf01ab3f202f6c78"

//This correctly returns: kfmjkaglpkmpfpbcmpabkldpcacpgmhi
$newStr = "";
$chars = str_split( $haystack );
for ( $i = 0, $length = count( $chars ); $i < $length; $i++ )
{
    $newStr .= $replace[ array_search( $chars[ $i ], $find ) ];
}
echo $newStr;

为什么第一个不正确?我使用它错了吗?

3 个答案:

答案 0 :(得分:3)

数组中的条目顺序.... str_replace()将按照它们在数组中出现的顺序处理每个数组条目,因此如果'1'替换为'b',那么'b'将随后被'l'取代;如果你想防止这种行为,请使用strtr()而不是str_replace()。

$find = array( "0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f" );
$replace = array( "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p" );
$haystack = "a5c9a06bfacf5f12cf01ab3f202f6c78" ;
echo strtr($haystack, array_combine($find, $replace));

您自己的代码只进行一次替换,因为它是针对您的字符串循环而不是针对from / to数组。

答案 1 :(得分:1)

Just use strtr

$haystack = "a5c9a06bfacf5f12cf01ab3f202f6c78" ;
echo strtr($haystack, implode($find), implode($replace));

Or preg_replace_callback

$find = array_flip($find);
echo preg_replace_callback('/[a-f0-9]/', function ($v) use($replace, $find) {
    return $replace[$find[$v[0]]];
}, $haystack);

输出

kfmjkaglpkmpfpbcmpabkldpcacpgmhi 

答案 2 :(得分:0)

正如@MarkBaker所指出的那样,答案是str_replace不是简单地在字符串中向前移动,而是像递归.replace()一样工作。相反,使用strtr(相当于Linux tr命令:

$tr = array( "0" => "a","1" => "b","2" => "c","3" => "d","4" => "e","5" => "f","6" => "g","7" => "h","8" => "i","9" => "j","a" => "k","b" => "l","c" => "m","d" => "n","e" => "o","f" => "p" );
$haystack = "a5c9a06bfacf5f12cf01ab3f202f6c78"

echo strtr( $haystack, $tr );