Skip to content

Instantly share code, notes, and snippets.

@theJinxrat
Created February 5, 2021 12:43
Show Gist options
  • Save theJinxrat/38e5abf31b198acb3693305694734ceb to your computer and use it in GitHub Desktop.
Save theJinxrat/38e5abf31b198acb3693305694734ceb to your computer and use it in GitHub Desktop.
Caesar Cipher Encode Decode (PHP)
<?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