PHP:将字符串的字符移动5个空格?这样A就变成了F,B就变成了G等等

标签 php string

如何将 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/

相关文章:

php - MySQL更新,使用PDO跳过空白字段

c - 使用 sscanf 从字符串中读取多个单词

c# - 结合两个整数来创建一个唯一的数字

c - 读取带有空格的字符串

php - 使用php将表单数据输入Mysql数据库

php - 超简单的 HTTP 套接字服务器,用 PHP 编写,表现出乎意料

c++ - 如何将 double 转换为字符串?

javascript - CSS 字符串 – 选择第三个逗号之前的所有内容

php - 每次登录更新散列盐是个好主意吗?

php - 在 PHP 函数中获取调用范围?