Skip to content

Instantly share code, notes, and snippets.

@tieutantan
Last active January 31, 2019 10:32
Show Gist options
  • Save tieutantan/6f6d96beddeab5e98a1a280472a7923d to your computer and use it in GitHub Desktop.
Save tieutantan/6f6d96beddeab5e98a1a280472a7923d to your computer and use it in GitHub Desktop.
Caesar Cipher Encryption in PHP
<?php
// test case in https://www.hackerrank.com/challenges/linkedin-practice-caesar-cipher/problem
$input = 'DNFjxo?b5h*5<LWbgs6?V5{3M].1hG)pv1VWq4(!][DZ3G)riSJ.CmUj9]7Gzl?VyeJ2dIPEW4GYW*scT8(vhu9wCr]q!7eyaoy.';
$step = 45;
foreach (range('a', 'z') as $value)
{
$az_lower[$i] = $value;
$az_upper[$i] = strtoupper($value);
}
$input_array = str_split($input);
foreach ($input_array as $character)
{
if (preg_match("/^[a-zA-Z]+$/", $character))
{
if (ctype_lower($character))
{
$position = array_search($character, $az_lower) + $step;
if ($position > 26)
{
$position = ($position % 26);
if ($position === 0)
{
$position = 26;
}
}
echo $az_lower[$position];
} else
{
$position = array_search($character, $az_upper) + $step;
if ($position > 26)
{
$position = ($position % 26);
if ($position === 0)
{
$position = 26;
}
}
echo $az_upper[$position];
}
} else
{
echo $character;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment