1

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

PHP方式:

$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 );

循环方式:

$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;

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

4

3 回答 3

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 数组。

于 2013-05-28T22:48:32.577 回答
1

只需使用 strtr

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

或 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 
于 2013-05-28T22:48:31.607 回答
0

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

$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 );
于 2013-05-28T22:48:13.327 回答