mirror of
https://github.com/TheAlgorithms/PHP.git
synced 2025-07-09 11:13:50 +02:00
38 lines
983 B
PHP
38 lines
983 B
PHP
<?php
|
|
|
|
// A mono-alphabetic cipher is a simple substitution cipher
|
|
// https://www.101computing.net/mono-alphabetic-substitution-cipher/
|
|
|
|
function monoAlphabeticCipher($key, $alphabet, $text)
|
|
{
|
|
$cipherText = ''; // the cipher text (can be decrypted and encrypted)
|
|
|
|
// check if the text length matches
|
|
if (strlen($key) != strlen($alphabet)) {
|
|
return false;
|
|
}
|
|
|
|
$text = preg_replace('/[0-9]+/', '', $text); // remove all the numbers
|
|
|
|
for ($i = 0; $i < strlen($text); $i++) {
|
|
$index = strripos($alphabet, $text[$i]);
|
|
if ($text[$i] == " ") {
|
|
$cipherText .= " ";
|
|
} else {
|
|
$cipherText .= ( ctype_upper($text[$i]) ? strtoupper($key[$index]) : $key[$index] );
|
|
}
|
|
}
|
|
|
|
return $cipherText;
|
|
}
|
|
|
|
function maEncrypt($key, $alphabet, $text)
|
|
{
|
|
return monoAlphabeticCipher($key, $alphabet, $text);
|
|
}
|
|
|
|
function maDecrypt($key, $alphabet, $text)
|
|
{
|
|
return monoAlphabeticCipher($alphabet, $key, $text);
|
|
}
|