Created
February 5, 2021 12:43
-
-
Save theJinxrat/38e5abf31b198acb3693305694734ceb to your computer and use it in GitHub Desktop.
Caesar Cipher Encode Decode (PHP)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function CaesarCipherDecode($string, $casas = 9) { | |
$abc = range('a', 'z'); | |
$decifrado = ''; | |
foreach (str_split(strtolower($string)) as $letter) { | |
if (ctype_alpha($letter)) { | |
foreach ($abc as $key => $alpha) { | |
if ($letter === $alpha) { | |
if (($key - $casas) < 0) { | |
$decifrado .= $abc[(($key - $casas) + count($abc))]; | |
} else { | |
$decifrado .= $abc[($key - $casas)]; | |
} | |
} | |
} | |
} else { | |
$decifrado .= $letter; | |
} | |
} | |
return $decifrado; | |
} | |
function CaesarCipherEncode($string, $casas = 9) { | |
$abc = range('a', 'z'); | |
$cifrado = ''; | |
foreach (str_split(strtolower($string)) as $letter) { | |
if (ctype_alpha($letter)) { | |
foreach ($abc as $key => $alpha) { | |
if ($letter === $alpha) { | |
if (($key + $casas) >= count($abc)) { | |
$cifrado .= $abc[(($key + $casas) - count($abc))]; | |
} else { | |
$cifrado .= $abc[($key + $casas)]; | |
} | |
} | |
} | |
} else { | |
$cifrado .= $letter; | |
} | |
} | |
return $cifrado; | |
} | |
$string = 'Jessica, eu te amo!'; | |
echo CaesarCipherEncode($string) . '<br />' . CaesarCipherDecode(CaesarCipherEncode($string)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment