简体   繁体   中英

PHP How can I replace the letter 'A' with spaces where the letter 'A' does not disappear, array to string?

I calculated modulo mathematics with the formula: 3 * n mod 26

by encrypting the array [n] AZ to the conversion of numbers, the results of the numbers are obtained from the results of a predetermined array, then the calculated results are converted back into a string.

Example: MY NAME IS CARL > KU NAKM YC GAZH

K = 10, U = 20, N = 13, A = 0, K = 10, M = 12

Y = 24, C = 2, G = 6, A = 0, Z = 25, H = 7

I have managed to convert numbers into strings and get a result: KUANAKMAYCAGAZH

What I want to ask is how to delete 'A' by replacing spaces, so the result is: 'KU NAKM YC GAZH' not 'KUANAKMAYCAGAZH'

Sorry, for my bad English.

Below is my script:

<?php
$text = 'MY NAME IS CARL';
$str = '';

$key = array(
"A" => 0, "B" => 1,"C" => 2, "D" => 3,"E" => 4,"F" => 5,
"G" => 6, "H" => 7, "I" => 8, "J" => 9, "K" => 10,
"L" => 11, "M" => 12, "N" => 13, "O" => 14,
"P" => 15, "Q" => 16, "R" => 17, "S" => 18,"T" => 19,
"U" => 20, "V" => 21, "W" => 22, "X" => 23,
"Y" => 24, "Z" => 25
);
for ($i = 0; $i < strlen($text); $i++) {
    $number = (3*$key[strtoupper($text[$i])])%26; // math caesar cipher 3 * n modulo 26
    $str .= array_search($number, $key);
}
echo $str;
?>

At the moment, you will get an error while trying to lookup the spaces in your array, you will get a message saying...

PHP Notice: Undefined index: in...

if you had error reporting turned on.

To solve this you can check that the character exists in the array before trying to encode it, otherwise just copy the character...

for ($i = 0; $i < strlen($text); $i++) {
    if ( isset($key[strtoupper($text[$i])]) ) {
        $number = (3*$key[strtoupper($text[$i])])%26; // math caesar cipher 3 * n modulo 26
        $str .= array_search($number, $key);
    }
    else {
        $str .= $text[$i];
    }
}

Rather than using an array of character => integer conversions, you could use the built-in ord and chr functions to create a translation function:

function translate_char($c) {
    $o = ord($c);
    if (in_array($c, range('A', 'Z'))) {
        return chr((($o - 65) * 3 % 26) + 65);
    }    
    elseif (in_array($c, range('a', 'z'))) {
        return chr((($o - 97) * 3 % 26) + 97);
    }
    else {
        return $c;
    }
}

This function also deals with lowercase alphabetic characters; if that is not required, simply remove the elseif clause. Any characters which are not alphabetic are returned unchanged.

You can then use array_map to apply this function to all the characters in $text :

$text = 'My name is Carl';
$str = implode('', array_map('translate_char', str_split($text)));
echo $str;

Output:

Ku nakm yc Gazh

Demo on 3v4l.org

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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