$a = array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
$b = array('2','y','X','b','q','9','n','E','5','m','O','D','z','I','B','w','g','x','U','j','W','1','6','T','N','V','k','t','P','J','a','Z','M','v','G','K','F','L','f','s','H','7','3','e','R','A','r','u','0','p','l','4','h','c','Y','S','o','d','C','i','Q','8');
$test = 'abcdefg';
$test = str_replace($a, $b, $test);
var_dump($test);
$test = str_replace($b, $a, $test);
var_dump($test);
exit;输出结果是
string(7) "lsrcu0g" string(7) "ODKRLMg" 第二个输出应该是abcdefg??

解决方案 »

  1.   

    呵呵,也不算bug吧。
    是要注意这一点的,有兴趣可以去读读源码,这个跟底层实现有关。
    echo str_replace(array('a','b'),array('b','0'),'a');//0 a->b->0
    echo str_replace(array('b','a'),array('0','b'),'a');//b,b->0,a->b注意替换顺序的区别
    //strtr最好不要用数组做替换参数,效率想对慢。
    echo strtr('a','ab','b0');//b
    echo strtr('a','ba','0b');//b
      

  2.   

    手册上就提到了...所以...不是bug
      

  3.   

    其实str_replace($array1,$array2,$string);的实现相当于for($array1 as $key=>$value){
        $string = str_replace($array[$key], $array2[$key],$string);
    }在$test = str_replace($array1,$array2,$string);后进行他的"逆过程"
    即$test = str_replace($array1,$array2,$test);后,出现$test != $string其实在于这个"逆"过程,有一个地方没有"逆"到.
    那就是$array1,$array2的数组顺序.
    如果在逆过程中按$array1, $array2 的数组的逆顺序进行替换,应该就会出现$test == $string以上纯属个人理论观点,至于正确性,还需要实践验证
      

  4.   


    有道理
    $a = array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
    $b = array ( 0 => 'o', 1 => '8', 2 => 'x', 3 => '7', 4 => '9', 5 => '2', 6 => 'A', 7 => 'j', 8 => 'U', 9 => 'E', 10 => 'P', 11 => 'J', 12 => '4', 13 => 'N', 14 => 'T', 15 => 'f', 16 => 'l', 17 => 'g', 18 => 'Z', 19 => 'v', 20 => 'n', 21 => 'W', 22 => 'i', 23 => 'V', 24 => 'q', 25 => 'H', 26 => 'Q', 27 => 't', 28 => 'm', 29 => 'C', 30 => '0', 31 => 'Y', 32 => 'e', 33 => 'u', 34 => 'L', 35 => '3', 36 => 'B', 37 => 'z', 38 => 'b', 39 => 'D', 40 => 'y', 41 => '6', 42 => 'k', 43 => 'K', 44 => 'X', 45 => 'w', 46 => 'R', 47 => 'G', 48 => 'h', 49 => 'c', 50 => 'F', 51 => 'a', 52 => 's', 53 => 'O', 54 => '1', 55 => 'I', 56 => 'd', 57 => 'p', 58 => 'M', 59 => '5', 60 => 'r', 61 => 'S', );$test = str_replace($a, $b, $test);
    echo $test.'<br>';
    $test = str_replace(array_reverse($b), array_reverse($a), $test);
    echo $test.'<br>';
    注意 $b 并不是随意排列的
    你可以这样得到:
    $b = $a;
    shuffle($b);
    $s = $test = 'abcdefg';
    $test = str_replace($a, $b, $test);
    echo $test.'<br>';
    $test = str_replace(array_reverse($b), array_reverse($a), $test);
    echo $test.'<br>';if($s == $test) {
     var_export($b);
    }