繁体   English   中英

PHP:将字符串的字符移位5个空格? 因此A变为F,B变为G等

[英]PHP: Shift characters of string by 5 spaces? So that A becomes F, B becomes G etc

如何在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个字典字符结束,但是由您来定义正确的字典并解决边缘情况。

  1. 一次迭代字符串,字符
  2. 获取字符的ASCII值
  3. 增加5点
  4. 添加到新字符串

这样的事情应该有效:

<?php
$newString = '';

foreach (str_split('test') as $character) {
    $newString .= chr(ord($character) + 5);
}

echo $newString;

请注意,迭代字符串的方法不止一种。

迭代字符,获取每个字符的ascii值,并获得ascii代码的char值,移动5:

function str_shift_chars_by_5_spaces($a) {
  for( $i = 0; $i < strlen($a); $i++ ) {
    $b .= chr(ord($a[$i])+5);};
  }
  return $b;
}

echo str_shift_chars_by_5_spaces("abc");

打印“fgh”

PHP有这个功能; 它被称为strtr()

$shifted = strtr( $string,
                  "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                  "FGHIJKLMNOPQRSTUVWXYZABCDE" );

当然,您可以同时执行小写字母和数字甚至符号:

$shifted = strtr( $string,
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+",
  "FGHIJKLMNOPQRSTUVWXYZABCDEfghijklmnopqrstuvwxyzabcde5678901234^&*()_+!@#$%" );

要反转转换,只需将最后两个参数交换为strtr()


如果需要动态更改移位距离,可以在运行时构建转换字符串:

$shift = 5;

$from = $to = "";
$sequences = array( "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz",
                    "0123456789", "!@#$%^&*()_+" );

foreach ( $sequences as $seq ) {
    $d = $shift % strlen( $seq );  // wrap around if $shift > length of $seq
    $from .= $seq;
    $to .= substr($seq, $d) . substr($seq, 0, $d);
}

$shifted = strtr( $string, $from, $to ); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM