Alex Alex - 10 days ago 7
PHP Question

Replace string letters with nth alphabet character in PHP

How can I replace the letters in a string with their +n corespondent from the alphabet?

For instance, replace each character with its +4 corespondent, as below:

a b c d e f g h i j k l m n o p q r s t u v w x y z
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
e f g h i j k l m n o p q r s t u v w x y z a b c d


So, if I have the string
johnny
, it should become
nslrrc
.

Answer

You could make a character-for-character replacement with strtr():

$shiftBy = 4;
$alphabet = 'abcdefghijklmnopqrstuvwxyz';

$newAlpha = substr($alphabet, $shiftBy) . substr($alphabet, 0, $shiftBy);

echo strtr("johnny", $alphabet, $newAlpha);

// nslrrc

Of course, this assumes all lowercase as in your example. Capitals complicate things.

http://codepad.viper-7.com/qNLli2

Bonus: also works with negative shifts