Skip to content

Instantly share code, notes, and snippets.

@adhocore
Created December 13, 2015 05:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adhocore/22389da5bcf3d2ba0c9c to your computer and use it in GitHub Desktop.
Save adhocore/22389da5bcf3d2ba0c9c to your computer and use it in GitHub Desktop.
map English alphabets to their position in qwerty layout keyboard, and reverse
<?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