需要一个关于如何从Accept-Language请求标头中获取首选语言的示例

时间:2021-11-24 05:22:48

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

我需要一个代码示例或库来解析Accept-Language标头并返回我的首选语言。 RFC2616声明:

The Accept-Language request-header field is similar to Accept, but restricts the set of natural languages that are preferred as a response to the request. Language tags are defined in section 3.10.

Accept-Language请求标头字段类似于Accept,但限制首选的自然语言集作为对请求的响应。语言标签在3.10节中定义。

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

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".

可以给每个语言范围赋予相关的质量值,该值表示用户对该范围指定的语言的偏好的估计。质量值默认为“q = 1”。

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.

进一步的阅读表明,有太多的“可选”,“应该”,“可能”和其他转动的言论阻止我重新发明* - 我想知道的是用户喜欢的语言,任何浏览器都会回答这个问题十亿次一天。

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

任何语言的任何代码片段(请使用Lisp和Assembler除外)都会有所帮助。

Many thanks in advance!

提前谢谢了!

2 个解决方案

#1


1  

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

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

$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);
    }
}

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
)

From example ACCEPT_LANGUAGE header : en-ca,en;q=0.8,en-us;q=0.6,de-de;q=0.4,de;q=0.2

例如ACCEPT_LANGUAGE标题:en-ca,en; q = 0.8,en-us; q = 0.6,de-de; q = 0.4,de; q = 0.2

Working example here

这里的工作示例

#2


31  

Solution:

namespace ConsoleApplication
{
    using System;
    using System.Linq;
    using System.Net.Http.Headers;

    class Program
    {
        static void Main(string[] args)
        {
            string header = "en-ca,en;q=0.8,en-us;q=0.6,de-de;q=0.4,de;q=0.2";
            var languages = header.Split(',')
                .Select(StringWithQualityHeaderValue.Parse)
                .OrderByDescending(s => s.Quality.GetValueOrDefault(1));
        }
    }
}

Result:

需要一个关于如何从Accept-Language请求标头中获取首选语言的示例

#1


1  

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

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

$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);
    }
}

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
)

From example ACCEPT_LANGUAGE header : en-ca,en;q=0.8,en-us;q=0.6,de-de;q=0.4,de;q=0.2

例如ACCEPT_LANGUAGE标题:en-ca,en; q = 0.8,en-us; q = 0.6,de-de; q = 0.4,de; q = 0.2

Working example here

这里的工作示例

#2


31  

Solution:

namespace ConsoleApplication
{
    using System;
    using System.Linq;
    using System.Net.Http.Headers;

    class Program
    {
        static void Main(string[] args)
        {
            string header = "en-ca,en;q=0.8,en-us;q=0.6,de-de;q=0.4,de;q=0.2";
            var languages = header.Split(',')
                .Select(StringWithQualityHeaderValue.Parse)
                .OrderByDescending(s => s.Quality.GetValueOrDefault(1));
        }
    }
}

Result:

需要一个关于如何从Accept-Language请求标头中获取首选语言的示例