note 93759 modified in function.str-rot13 by danbrown

From: Date: Sat, 26 Sep 2009 22:56:20 +0000
Subject: note 93759 modified in function.str-rot13 by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-161102@lists.php.net to get a copy of this message
Here's my implementation of a str_rot that takes a custom offset. It's faster than the others here because it allocates the output string in one go instead of tacking on characters one at a time. It can handle positive or negative offsets of any size, and it fixes everything up to ensure only upper and lower case letters are translated and that they wrap around correctly within the alphabet. <?php function str_rot($s, $n = 13) { $n = (int)$n % 26; if (!$n) return $s; for ($i = 0, $l = strlen($s); $i < $l; $i++) { $c = ord($s[$i]); if ($c >= 97 && $c <= 122) { $s[$i] = chr(($c - 71 + $n) % 26 + 97); } else if ($c >= 65 && $c <= 90) { $s[$i] = chr(($c - 39 + $n) % 26 + 65); } } return $s; } ?> --was-- Here's my implementation of a str_rot that takes a custom offset. It's faster than the others here because it allocates the output string in one go instead of tacking on characters one at a time. It can handle positive or negative offsets of any size, and it fixes everything up to ensure only upper and lower case letters are translated and that they wrap around correctly within the alphabet. function str_rot($s, $n = 13) { $n = (int)$n % 26; if (!$n) return $s; for ($i = 0, $l = strlen($s); $i < $l; $i++) { $c = ord($s[$i]); if ($c >= 97 && $c <= 122) { $s[$i] = chr(($c - 71 + $n) % 26 + 97); } else if ($c >= 65 && $c <= 90) { $s[$i] = chr(($c - 39 + $n) % 26 + 65); } } return $s; } http://php.net/manual/en/function.str-rot13.php

« previous php.notes (#161102) next »