如何使用php将角色转换为z或z?

时间:2017-05-14 15:34:00

标签: php

$string = "abcfght";
$shift = 3;
$shiftedString = "";

for ($i = 0; $i < strlen($string); $i++)
{
    $ascii = ord($string[$i]);
    $shiftedChar = chr($ascii-$shift);

    $shiftedString .= $shiftedChar;
}

echo $shiftedString;
  

在上面的代码中,b移位-3,所以根据asci表显示输出,但我的期望是输出“z”

1 个答案:

答案 0 :(得分:0)

试试这个,查看live demo

$string = "abcfght";
$shift = 3;
$chars = str_split($string);
$arr = array_map(function($v){
  $shift = ord($v) -3;
  echo $shift."\n";
  return $shift < 97 ? chr($shift + 26) : chr($shift);
}, $chars);
echo implode('', $arr);