Created
December 13, 2015 05:06
-
-
Save adhocore/22389da5bcf3d2ba0c9c to your computer and use it in GitHub Desktop.
map English alphabets to their position in qwerty layout keyboard, and reverse
This file contains 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 | |
/* | |
* QWERTY encode decode | |
* | |
* qwerty_encode maps English alphabets to their | |
* position in qwerty layout keyboard like so: | |
* a -> q, b -> w, c -> e ... etc | |
* | |
* qwerty_decode does the reverse | |
*/ | |
function qwerty_map() | |
{ | |
$q = 'qwertyuiopasdfghjklzxcvbnm'; | |
return array_combine( | |
array_merge(range('a', 'z'), range('A', 'Z')), | |
str_split($q.strtoupper($q)) | |
); | |
} | |
function qwerty_encode($str) | |
{ | |
if (!is_string($str) or !preg_match('/[a-z]/i', $str)) { | |
return $str; | |
} | |
$ret = ''; | |
$map = qwerty_map(); | |
foreach (str_split($str) as $chr) { | |
$ret .= isset($map[$chr]) ? $map[$chr] : $chr; | |
} | |
return $ret; | |
} | |
function qwerty_decode($str) | |
{ | |
if (!is_string($str) or !preg_match('/[a-z]/i', $str)) { | |
return $str; | |
} | |
$ret = ''; | |
$map = array_flip(qwerty_map()); | |
foreach (str_split($str) as $chr) { | |
$ret .= isset($map[$chr]) ? $map[$chr] : $chr; | |
} | |
return $ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment