[英]Replace string letters with nth alphabet character in PHP
如何用字母表中的+ n corespondent替换字符串中的字母?
例如,用+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
。
<?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;
?>
这是一种方式:
<?php
$newStr = "";
$str = "johnny";
define('DIFF', 4);
for($i=0; $i<strlen($str); $i++) {
$newStr .= chr((ord($str[$i])-97+DIFF)%26+97);
}
您可以使用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
奖金:也适用于负面转变
制作一系列字母。 对于数组[$ key]值中的每个字母,echo数组[$ key + 4]。 如果$ key + 4大于数组的大小,请执行一些基本计算并将其转发以启动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.