Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Last active August 10, 2024 00:22
Show Gist options
  • Save xeoncross/dc2ebf017676ae946082 to your computer and use it in GitHub Desktop.
Save xeoncross/dc2ebf017676ae946082 to your computer and use it in GitHub Desktop.
Parse the HTTP except language header
<?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
}
}
<?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;
// $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