Unfortunately, none of the answers to this question takes into account some valid HTTP_ACCEPT_LANGUAGE
such as:
q=0.8,en-US;q=0.5,en;q=0.3
: having the q
priority value at first place.ZH-CN
: old browsers that capitalise (wrongly) the whole langcode.*
: that basically say "serve whatever language you have".After a comprehensive test with thousands of different Accept-Languages in my server, I ended up having this language detection method:
define('SUPPORTED_LANGUAGES', ['en', 'es']);
function detect_language() {
foreach (preg_split('/[;,]/', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $sub) {
if (substr($sub, 0, 2) == 'q=') continue;
if (strpos($sub, '-') !== false) $sub = explode('-', $sub)[0];
if (in_array(strtolower($sub), SUPPORTED_LANGUAGES)) return $sub;
}
return 'en';
}