ROT13 transform

Simple example of the ROT13 algorithm. ROT13 is a simple function which rotates the
characters of a string 13 places forward.

Hint: Since PHP 4+ you can use the PHP build-in function str_rot13.
This is just a example implementation to show how it works.

Snippet information

Author:
Chris Heschong

License:
Not given

Language:
PHP

Created:
04/17/2006

Updated:
12/10/2007

Tags:
,

Related links:
- Snippet source
- Wikipedia page
- ROT13 page


/**
 * ROT13 is a simple function which rotates the 
 * characters of a string 13 places forward.
 *
 * @param     string    $string         Input string
 * @return    string     Encrypted string     
 */ 
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;
}


Found a bug? Or do you have a better solution for this?
Feel free to leave a message:

Add a comment


Leave a comment

Anonymous September 24, 2009 at 06:34
http://php.net/str_rot13
Ind3X July 13, 2009 at 08:58
I think your solution is very complicated...

My solution:

function asciicesar15_crypt($uncrypted_password) {
$crypted_pw ="";
$strl_lng = strlen($uncrypted_password);
for($count = 0; $count < $strl_lng; $count++){
$digit = substr($uncrypted_password, $count);
$newdigit = chr(ord($digit) - 13);
$crypted_pw = $crypted_pw . $newdigit;
}
return $crypted_pw;
}

function asciicesar15_decrypt($uncrypted_password) {
$crypted_pw ="";
$strl_lng = strlen($uncrypted_password);
for($count = 0; $count < $strl_lng; $count++){
$digit = substr($uncrypted_password, $count);
$newdigit = chr(ord($digit) + 13);
$crypted_pw = $crypted_pw . $newdigit;
}
return $crypted_pw;
}
Cameron June 25, 2008 at 09:59
instead of strlen($string) in the for() loop, do $len = strlen($string); and for( $i=0; $i<$len; $i++ ) that way your not calling strlen() for EVERY loop wasting valuable CPU time