I found a string after reading funny things about Jon Skeet, and I guessed that it was in ROT13. Before just checking my guess, I thought I’d try and decrypt it with PHP. Here’s what I had:
$string = "Vs lbh nfxrq Oehpr Fpuarvre gb qrpelcg guvf, ur'q pehfu lbhe fxhyy jvgu uvf ynhtu.";
$tokens = str_split($string);
for ($i = 1; $i <= sizeof($tokens); $i++) {
$char = $tokens[$i-1];
for ($c = 1; $c <= 13; $c++) {
$char++;
}
echo $char;
}
My string comes back as AIaf you aasakaead ABruacae Sacahnaeaiaer to adaeacrypt tahais, ahae'ad acrusah your sakualal waitah ahais alaauagah.
My logic seems quite close, but it’s obviously wrong. Can you help me with it?
Here is a working implementation, without using the nested loop. You also don’t need to split the string into an array, since you can index individual characters just like an array with strings in PHP.
You need to know that ASCII upper-case characters range from 65 – 99, and lower-case characters range from 97 – 122. If the current character is in one of those ranges, add 13 to its ASCII value. Then, you check if you should have rolled over to the beginning of the alphabet. If you should’ve rolled over, subtract 26.
This produces: