Reputation: 5685
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
.
Upvotes: 0
Views: 2199
Reputation: 20873
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
Upvotes: 1
Reputation: 527
This is a way:
<?php
$newStr = "";
$str = "johnny";
define('DIFF', 4);
for($i=0; $i<strlen($str); $i++) {
$newStr .= chr((ord($str[$i])-97+DIFF)%26+97);
}
Upvotes: 1
Reputation: 3338
Make an array of letters. For each letter in array[$key] value, echo array[$key+4]. If the $key+4 is bigger than the size of array, do some basic calculations and forward it to start.
Upvotes: -1
Reputation: 5191
<?php
$str="abcdefghijklmnopqrstuvwxyz";
$length=strlen($str);
$ret = "";
$n=5;
$n=$n-1;
for($i = 0, $l = strlen($str); $i < $l; ++$i)
{
$c = ord($str[$i]);
if (97 <= $c && $c < 123) {
$ret.= chr(($c + $n + 7) % 26 + 97);
} else if(65 <= $c && $c < 91) {
$ret.= chr(($c + $n + 13) % 26 + 65);
} else {
$ret.= $str[$i];
}
}
echo $ret;
?>
DEMO 1 (Eg: abcdefghijklmnopqrstuvwxyz)
Upvotes: 1