Skip to content

Instantly share code, notes, and snippets.

@jonathanlaf
Last active August 14, 2018 12:53
Show Gist options
  • Save jonathanlaf/e1adb18b4b615bd8a2f355932514a51e to your computer and use it in GitHub Desktop.
Save jonathanlaf/e1adb18b4b615bd8a2f355932514a51e to your computer and use it in GitHub Desktop.
[Keyboard char to Ascii] Take care of different ASCII Code returned by a single caracter depending on Keyboard layout. #encoding #php #ascii
<?php
/*
* Accept array or string
*/
function convertSameCaracterToSameAscii($string)
{
$tab_chr = array() ;
for($control = 0; $control < 32; $control++) {
if ($control != 9 && $control != 10) {
$tab_chr[]= chr($control) ;
}
}
return str_replace($tab_chr, '', $string);
}
// Source : http://php.net/manual/en/function.chr.php#107742
<?php
function getAsciiCode($string)
{
$implode = false;
if (!is_array($string))
{
$implode = true;
$string = explode(' ', $string);
}
$c = count($string);
for($i=0;$i<$c;$i++)
{
$output[] = ord($string[$i]);
}
if ($implode)
{
return implode(' ', $output);
}
return $output;
}
/*
* usage with array
*/
/*Print input*/
$caracters = ["?","?","?"];
echo "Array input : \r\n";
print_r($caracters);
echo "\r\n";
print_r(getAsciiCode($caracters));
echo "\r\n";
/*Convert*/
$string = convertSameCaracterToSameAscii($caracters);
/*Print output*/
echo "Array output : \r\n";
print_r($string);
print_r(getAsciiCode($string));
echo "\r\n";
/*
* usage with string
*/
/*Print input*/
$caracters = "? ? ?";
echo "String input : \r\n";
print_r($caracters);
echo "\r\n";
print_r(getAsciiCode($caracters));
echo "\r\n";
/*Convert*/
$string = convertSameCaracterToSameAscii($caracters);
/*Print output*/
echo "String output : \r\n";
print_r($string);
print_r(getAsciiCode($string));
echo "\r\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment