Need an example on how to get preferred language from Accept-Language request header

前端 未结 2 1267
我在风中等你
我在风中等你 2020-12-31 06:37

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

The Acc

相关标签:
2条回答
  • 2020-12-31 07:09

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

    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

    Working example here

    0 讨论(0)
  • 2020-12-31 07:13

    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:

    enter image description here

    0 讨论(0)
提交回复
热议问题