Rot13 Function In PHP

Rot13 (which stands for "rotate by 13 places") is a name given to a simple encoding algorithm (or substitution cipher) that is used to mask text. It works by making each letter 13 spaces further along in the alphabet so that a becomes n and b becomes o. For the letter n the alphabet starts again from the beginning.

The cipher can be used both ways so that any string encoded with the function can then be easily decoded with the same function. For this reason it is a very poor mechanism of encoding, but can be used if you want to mask some text but are not concerned about people reading it. It is commonly used on forums in order to hide spoilers and solutions from readers who don't want to see them.

Here is the function.

function Rot13($string){
 for($i=0; $i < strlen($string); $i++){
  $c = ord($string[$i]);
  
  if($c >= ord('n') & $c <= ord('z') | $c >= ord('N') & $c <= ord('Z')){
   $c -= 13;
  }elseif($c >= ord('a') & $c <= ord('m') | $c >= ord('A') & $c <= ord('M')){
   $c += 13;
  }
  $string[$i] = chr($c);
 }
 
 return $string;
}

Use the function in the following way.

echo Rot13('this is a string');

This prints out guvf vf n fgevat, which can then be put back into the function to get the original string.

Comments

Or you could use str_rot13() from the standard library

Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
9 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.