开发者

Parsing HTTP_ACCEPT_LANGUAGE

开发者 https://www.devze.com 2023-03-26 19:07 出处:网络
I came across a script that parses HTTP_ACCEPT_LANGUAGE: http://www.thefutureoftheweb.com/blog/use-accept-language-header

I came across a script that parses HTTP_ACCEPT_LANGUAGE: http://www.thefutureoftheweb.com/blog/use-accept-language-header

this script returns an ORDERED array containing the acceptable开发者_如何学运维 langs:

Array ( [it] => 1 [ar] => 0.8 [ja] => 0.6 [cn] => 0.4 [de] => 0.2 )

Now, I want to make an array containing the available languages like that:

$av_lang = array('en','fr','de','it'); (unordered array)

Then I want to loop through the first array and get the first key that is in the second array.

For example, it takes 'en' from the first array and check if present in the second array, if not, go to the next key 'ar' and check it. if none of them, return a default lang like 'en'.

Finally I want to get one of the available langs in $av_lang.

Thanks.


Personally I use something like this:

$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
preg_match_all('/(\W|^)([a-z]{2})([^a-z]|$)/six', $lang, $m, PREG_PATTERN_ORDER);
$user_langs = $m[2];

What you are given is an array of 2-letter languages, you can then loop through them and find a language that you support, ie

$supported_langs = array('en', 'fr', 'de', 'it');
$user_lang = 'en'; // Default
foreach($user_langs AS $tmp){
    if(in_array($tmp, $supported_langs)){
        $user_lang = $tmp;
        break;
    }
}

At this point $user_lang will now contain the first supported language from the header (or the default)


Try something like this:

$lang = array('it' => 1, 'ar' => 0.8, 'ja' => 0.6, 'cn' => 0.4, 'de' => 0.2);
$preferred = array('en', 'ja');

$intersect = array_values(array_intersect(array_keys($lang), $preferred));

if (isset($intersect[0])) {
    echo $intersect[0]; // returns ja
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号