2013-03-26 157 views
0

如何用字母中的+ n corespondent替換字符串中的字母?用PHP中的第n個字母字符替換字符串字母

例如,以其+4 corespondent如下替換每個字符:

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 

所以,如果我有串johnny,它應該成爲nslrrc

+0

所以,你嘗試過什麼? – lanzz 2013-03-26 21:55:32

+2

http://www.whathaveyoutried.com – 2013-03-26 21:55:50

+2

13很簡單[rot13()](http://php.net/manual/en/function.str-rot13.php)。 <提示請參閱用戶註釋 – 2013-03-26 21:59:13

回答

1

你可以做一個字符的字符替換爲strtr()

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

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

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

// nslrrc 

。當然,這是假設所有小寫在你的榜樣。首都使事情複雜化。

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

獎勵:還與負轉變

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

-1

使字母的排列。對於數組[$ key]值中的每個字母,echo數組[$ key + 4]。如果$ key + 4大於數組的大小,則執行一些基本計算並轉發它開始。

1

這是一個辦法:

<?php 

$newStr = ""; 
$str = "johnny"; 

define('DIFF', 4); 
for($i=0; $i<strlen($str); $i++) {   
    $newStr .= chr((ord($str[$i])-97+DIFF)%26+97); 
} 
相關問題