Detect user language with PHP


/ Published in: PHP
Save to your folder(s)

Function to detect user language in php.


Copy this code and paste it in your HTML
  1. function getPreferredLanguage() {
  2. $langs = array();
  3. if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  4. // break up string into pieces (languages and q factors)
  5. preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i',
  6. $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse);
  7. if (count($lang_parse[1])) {
  8. // create a list like "en" => 0.8
  9. $langs = array_combine($lang_parse[1], $lang_parse[4]);
  10. // set default to 1 for any without q factor
  11. foreach ($langs as $lang => $val) {
  12. if ($val === '') $langs[$lang] = 1;
  13. }
  14. // sort list based on value
  15. arsort($langs, SORT_NUMERIC);
  16. }
  17. }
  18. //extract most important (first)
  19. foreach ($langs as $lang => $val) { break; }
  20. //if complex language simplify it
  21. if (stristr($lang,"-")) {$tmp = explode("-",$lang); $lang = $tmp[0]; }
  22. return $lang;
  23. }

URL: http://www.barattalo.it/2009/12/16/detect-user-language-with-php/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.