Skip to content

Instantly share code, notes, and snippets.

@adhocore
Created Dec 13, 2015
Embed
What would you like to do?
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