Alex Alex - 1 year ago 75
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
, it should become

Answer Source

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.

Bonus: also works with negative shifts

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download