2

This works up until the 13th character is hit. Once the str_ireplace hits "a" in the cyper array, the str_ireplace stops working.

Is there a limit to how big the array can be? Keep in mind if type "abgf" i get "nots", but if I type "abgrf" when I should get "notes" I get "notrs". Racked my brain cant figure it out.

$_cypher = array("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");

$_needle = array("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");


$_decryptedText = str_ireplace($_cypher, $_needle, $_text);
echo $_decryptedText;

Help?

Brad
  • 159,648
  • 54
  • 349
  • 530
user-44651
  • 3,924
  • 6
  • 41
  • 87

4 Answers4

5

Use strtrDocs:

$_text = 'abgrf';

$translate = array_combine($_cypher, $_needle);

$_decryptedText = strtr($_text, $translate);

echo $_decryptedText; # notes

Demo


But, was there something I was doing wrong?

It will replace each pair, one pair after the other on the already replaced string. So if you replace a character that you replace again, this can happen:

    r -> e   e -> r
abgrf -> notes -> notrs

Your e-replacement comes after your r-replacement.

hakre
  • 193,403
  • 52
  • 435
  • 836
  • Ah. So like @ircmaxell said, it's doing a circular replacement. Is other than using str_rot13 is there a way to complete the task as I have it? – user-44651 Oct 14 '11 at 18:16
  • @Firemarble: As written `strtr`. I added an example. – hakre Oct 14 '11 at 18:19
2

Take a peak at the docs for str_replace. Namely the following line:

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.

So it's working as told. It's just doing a circular replacement (n -> a, then a -> n).

ircmaxell
  • 163,128
  • 34
  • 264
  • 314
1

Use str_rot13

nachito
  • 6,975
  • 2
  • 25
  • 44
0

although it appears to be a straight rot13, if it is not, another option is to use strtr(). You provide a string and an array of replacement pairs and get the resulting translation back.

Jonathan Kuhn
  • 15,279
  • 3
  • 32
  • 43