简体   繁体   中英

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 .

<?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)

DEMO 2 (Eg: johhny)

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);
}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM