如何将 PHP 中的字符串字符移动 5 个空格?
所以说:
A 变成 F
B 变成 G
Z 变成 E
与符号相同:
!@#$%^&*()_+
所以 !变成 ^
% 变为 )
等等。
无论如何都要这样做吗?
最佳答案
其他答案使用 ASCII 表(这很好),但我的印象是这不是您想要的。这个利用了 PHP 访问字符串字符的能力,就像字符串本身是一个数组一样,允许您拥有自己的字符顺序。
首先,定义你的字典:
// for simplicity, we'll only use upper-case letters in the example
$dictionary = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
然后检查输入字符串的字符,并将每个字符替换为字典中的 $position + 5
:
$input_string = 'STRING';
$output_string = '';
$dictionary_length = strlen($dictionary);
for ($i = 0, $length = strlen($input_string); $i < $length; $i++)
{
$position = strpos($dictionary, $input_string[$i]) + 5;
// if the searched character is at the end of $dictionary,
// re-start counting positions from 0
if ($position > $dictionary_length)
{
$position = $position - $dictionary_length;
}
$output_string .= $dictionary[$position];
}
$output_string
现在将包含您想要的结果。
当然,如果 $input_string
中的字符不存在于 $dictionary
中,那么它始终会成为第 5 个字典字符,但这取决于您定义一个合适的字典并解决边缘情况。
关于PHP:将字符串的字符移动5个空格?这样A就变成了F,B就变成了G等等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26487438/