Auto language selection


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

Auto language selection based on site languages and user preferences.


Copy this code and paste it in your HTML
  1. <?php
  2. /*
  3.   determine which language out of an available set the user prefers most
  4.  
  5.   $available_languages array with language-tag-strings (must be lowercase) that are available
  6.   $http_accept_language a HTTP_ACCEPT_LANGUAGE string (read from $_SERVER['HTTP_ACCEPT_LANGUAGE'] if left out)
  7. */
  8. function prefered_language ($available_languages,$http_accept_language="auto") {
  9. // if $http_accept_language was left out, read it from the HTTP-Header
  10. if ($http_accept_language == "auto") $http_accept_language = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
  11.  
  12. // standard for HTTP_ACCEPT_LANGUAGE is defined under
  13. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
  14. // pattern to find is therefore something like this:
  15. // 1#( language-range [ ";" "q" "=" qvalue ] )
  16. // where:
  17. // language-range = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" )
  18. // qvalue = ( "0" [ "." 0*3DIGIT ] )
  19. // | ( "1" [ "." 0*3("0") ] )
  20. preg_match_all("/([[:alpha:]]{1,8})(-([[:alpha:]|-]{1,8}))?" .
  21. "(\s*;\s*q\s*=\s*(1\.0{0,3}|0\.\d{0,3}))?\s*(,|$)/i",
  22. $http_accept_language, $hits, PREG_SET_ORDER);
  23.  
  24. // default language (in case of no hits) is the first in the array
  25. $bestlang = $available_languages[0];
  26. $bestqval = 0;
  27.  
  28. foreach ($hits as $arr) {
  29. // read data from the array of this hit
  30. $langprefix = strtolower ($arr[1]);
  31. if (!empty($arr[3])) {
  32. $langrange = strtolower ($arr[3]);
  33. $language = $langprefix . "-" . $langrange;
  34. }
  35. else $language = $langprefix;
  36. $qvalue = 1.0;
  37. if (!empty($arr[5])) $qvalue = floatval($arr[5]);
  38.  
  39. // find q-maximal language
  40. if (in_array($language,$available_languages) && ($qvalue > $bestqval)) {
  41. $bestlang = $language;
  42. $bestqval = $qvalue;
  43. }
  44. // if no direct hit, try the prefix only but decrease q-value by 10% (as http_negotiate_language does)
  45. else if (in_array($langprefix,$available_languages) && (($qvalue*0.9) > $bestqval)) {
  46. $bestlang = $langprefix;
  47. $bestqval = $qvalue*0.9;
  48. }
  49. }
  50. return $bestlang;
  51. }
  52. ?>

URL: http://de2.php.net/manual/en/function.http-negotiate-language.php#

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.