str_rot13

(PHP 4 >= 4.2.0, PHP 5)

str_rot13 — Perform the rot13 transform on a string

Description

stringstr_rot13
( string$str
)

Performs the ROT13 encoding on the str argument and
returns the resulting string.

The ROT13 encoding simply shifts every letter by 13 places in the alphabet
while leaving non-alpha characters untouched. Encoding and decoding are
done by the same function, passing an encoded string as argument will
return the original version.

Parameters

str

The input string.

Return Values

Returns the ROT13 version of the given string.

Examples

User Contributed Notes 8 notes

I was reminded again of the desire for a generic str_rot function. Character manipulation loops in PHP are slow compared to their C counterparts, so here's a tuned version of the previous function I posted. It's 1.6 times as fast, mainly by avoiding chr() calls.

This technique is faster because PHP's strtr is implemented in C using a byte lookup table (it has O(m + n) complexity). However, PHP 6 will use Unicode, so I guess(?) strtr will then have to be implemented with a search for each character (O(m * n)). Using strtr might still be faster since it offloads the character manipulation to C rather than PHP, but I don't really know. Take your pick.

This ROT13 variant is different from my earlier version in that it retains 'ethnicity'. For example, a Chinese text when encrypted will remain Chinese, and the string will not be making sense (the real meaning will be encrypted). Just look at the code and you will understand.

/* * Check if the character is within the bounds of our function (a-zA-z) * if not it gets tacked on to the string as is and we move on to the * next one. */if( $c<$u_lower || $c>$l_upper || ( $c>$u_upper && $c <$l_lower ) ){$newstr .= chr($c); continue; }

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.