簡體   English   中英

在PHP中用第n個字母字符替換字符串字母

[英]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;
?>

DEMO 1(例如:abcdefghijklmnopqrstuvwxyz)

DEMO 2(例如:johhny)

這是一種方式:

<?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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM