str_replace () not working correctly with generated arrays

2

Follow the code:

$minu = range("a", "z");
$maiu = range("A", "Z");

$letras = array_merge($minu, $maiu);

$minusculas = array_merge($minu, $maiu);

When doing a str_replace($Lminusculas, $Lmaiusculas, "TesteSimples"); the following is returned:

  

lerveSimvses

And, while doing a str_replace($Lmaiusculas, $Lminusculas, "lerveSimvses"); the following is returned:

  

TistERUephes

However, I wanted to make the second str_replace() a string go back to the initial state SimpleType .

    
asked by anonymous 05.06.2015 / 00:50

1 answer

1

If I understand correctly, your intent with the code is to "encrypt" the string, changing 'A' and 'Z', 'B' and 'Y', ...? If so, the problem is that str_replace makes the substitutions "in order"; I think it's more semantic to use strtr , which does what you want and operates on each byte individually, and so is probably more efficient:

<?php

$antes = implode(array_merge(range('a', 'z'), range('A', 'Z')));
$depois = implode(array_merge(range('z', 'a'), range('Z', 'A')));

echo strtr('Stack Overflow', $antes, $depois) . "\n";
echo strtr('Hgzxp Leviuold', $antes, $depois) . "\n";

?>
    
05.06.2015 / 01:47