str_replace() not working properly with generated arrays

Asked

Viewed 48 times

2

Follows the code:

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

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

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

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

lerveSimvses

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

Tisteruephes

However, I wanted to do that by doing the second str_replace() to string returned to initial state Testesimples.

1 answer

1


If I understand correctly, your intention with the code is to "encrypt" the string, by swapping A' and Z', B' and Y', ...? If so, the problem is that the str_replace makes the substitutions "in order"; I think it’s more semantic to use strtr, which does what you want and operates over 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";

?>
  • (naturally, this "encryption" will choke if the string has accented characters)

  • You will not have accented characters, only minute and upper case, @ctgpi. Regarding your answer, my intention is rather to "encrypt" the string. I changed my str_replace for strtr but neither "encryption" nor "decryption". Remembering that my code remains the same as the question, only replaces the functions (str_replace for strtr).

  • To strtr with three parameters accepts strings, not arrays, and the order of the parameters is different; you will have to implodego to the arrays before calling the strtr, that even I didn’t do in my code.

  • Ah, that’s right! The implode, worked perfectly! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.