Rot13 Function In PHP

14th May 2008 - 2 minutes read time

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.

  1. function Rot13($string){
  2. for($i=0; $i < strlen($string); $i++){
  3. $c = ord($string[$i]);
  4.  
  5. if($c >= ord('n') & $c <= ord('z') | $c >= ord('N') & $c <= ord('Z')){
  6. $c -= 13;
  7. }elseif($c >= ord('a') & $c <= ord('m') | $c >= ord('A') & $c <= ord('M')){
  8. $c += 13;
  9. }
  10. $string[$i] = chr($c);
  11. }
  12.  
  13. return $string;
  14. }

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

Permalink

Or you could use str_rot13() from the standard library

Anonymous (Thu, 10/27/2011 - 14:52)

Add new comment

The content of this field is kept private and will not be shown publicly.