Using the PHP HTTP_ACCEPT_LANGUAGE server variable

后端 未结 7 1375
梦毁少年i
梦毁少年i 2020-11-29 00:07

I created a PHP script that checks the HTTP_ACCEPT_LANGUAGE and loads the website using the appropriate language from the 1st two characters:

          $http         


        
7条回答
  •  既然无缘
    2020-11-29 00:26

    In the end I went with this solution:

    if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
      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])){
        $langs = array_combine($lang_parse[1], $lang_parse[4]);
        foreach ($langs as $lang => $val){
          if ($val === '') $langs[$lang] = 1;
        }
        arsort($langs, SORT_NUMERIC);
      }
      foreach ($langs as $lang => $val){
        if (strpos($lang,'en')===0){
          $language = 'english';
          break;
        } else if (strpos($lang,'es')===0){
          $language = 'spanish';
        }
      }
    }
    

    I would like to thank AJ for the links. Also thanks to all that replied.

提交回复
热议问题