本文介绍了需要关于如何得到的Accept-Language请求头preferred语言的例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个code例子或库,将解析接受语言头,回到了我preferred语言。 RFC2616 说:

I need a code example or library which would parse Accept-Language header and return me preferred language.RFC2616 states that:

在Accept-Language请求标头字段类似于Accept,但是  限制集自然语言是pferred为$ P $的  响应于该请求。语言标签在3.10节定义。

   Accept-Language = "Accept-Language" ":"
                     1#( language-range [ ";" "q" "=" qvalue ] )
   language-range  = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" )

每个语言范围内,可给予相关的质量值  再presents用户的preference的语言估计  由该范围内指定。质量值默认为Q = 1。

Each language-range MAY be given an associated quality value which represents an estimate of the user's preference for the languages specified by that range. The quality value defaults to "q=1".

延伸阅读表明,有太多的可选,应该,可能和演讲中指出$ P $的其他轮流从重新发明轮子pvent我 - 我所想知道的是什么语言的用户prefers,任何浏览器回答了这个问题,每天十亿倍。

Further reading shows that there are too many "optional", "should", "may" and other turns of speech that prevent me from reinventing the wheel - all I want to know is what language user prefers, any browser answers this question billion times a day.

在任何语言中的任何code段(除Lisp和汇编,请)将是有益的。

Any code snippet in any language (except Lisp and Assembler please) would be helpful.

提前感谢!

推荐答案

试试这个,它在PHP,但使用相同的正则表达式我敢肯定,它适用于任何语言:

Try this, its in PHP but using the same regex i'm sure its adaptable to any language :

$langs = array(); // used to store values

if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
    // break up string into pieces (languages and q factors)
    preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse);

    if (count($lang_parse[1])) {
        // create a list like "en" => 0.8
        $langs = array_combine($lang_parse[1], $lang_parse[4]);

        // set default to 1 for any without q factor
        foreach ($langs as $lang => $val) {
            if ($val === '') $langs[$lang] = 1;
        }

        // sort list based on value
        arsort($langs, SORT_NUMERIC);
    }
}

产生一个排序的数组preferred语言第一:

produces a sorted array with preferred language first :

Array
(
    [en-ca] => 1
    [en] => 0.8
    [en-us] => 0.6
    [de-de] => 0.4
    [de] => 0.2
)

从例如 ACCEPT_LANGUAGE 标题: EN-CA,连接; Q = 0.8,EN-US; Q = 0.6,去德;问= 0.4,日; Q = 0.2

工作实例

Working example here

这篇关于需要关于如何得到的Accept-Language请求头preferred语言的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!