Last active
August 10, 2024 00:22
-
-
Save xeoncross/dc2ebf017676ae946082 to your computer and use it in GitHub Desktop.
Parse the HTTP except language header
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 | |
function prefered_language($available_languages, $http_accept_language) { | |
$available_languages = array_flip($available_languages); | |
$langs = array(); | |
preg_match_all('~([\w-]+)(?:[^,\d]+([\d.]+))?~', strtolower($http_accept_language), $matches, PREG_SET_ORDER); | |
foreach($matches as $match) { | |
list($a, $b) = explode('-', $match[1]) + array('', ''); | |
$value = isset($match[2]) ? (float) $match[2] : 1.0; | |
if(isset($available_languages[$match[1]])) { | |
$langs[$match[1]] = $value; | |
continue; | |
} | |
if(isset($available_languages[$a])) { | |
$langs[$a] = $value - 0.1; | |
} | |
} | |
if($langs) { | |
arsort($langs); | |
return key($langs); // We don't need the whole array of choices since we have a match | |
} | |
} |
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 | |
//$_SERVER["HTTP_ACCEPT_LANGUAGE"] = 'en-us,en;q=0.8,es-cl;q=0.5,zh-cn;q=0.3'; | |
// Languages we support | |
$available_languages = array("en", "zh-cn", "es"); | |
$lang = prefered_language($available_languages, $_SERVER["HTTP_ACCEPT_LANGUAGE"]); | |
print "<pre>Debug\n"; | |
print_r($available_languages); | |
print_r(explode(',', $_SERVER["HTTP_ACCEPT_LANGUAGE"])); | |
print $lang; |
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
// $available_languages | |
Array | |
( | |
[0] => en | |
[1] => zh-cn | |
[2] => es | |
) | |
// $_SERVER["HTTP_ACCEPT_LANGUAGE"] | |
Array | |
( | |
[0] => en-us | |
[1] => en;q=0.8 | |
[2] => es-cl;q=0.5 | |
[3] => zh-cn;q=0.3 | |
) | |
// Result | |
en |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment