Source of: get_lang.php (Download Source)
Last Modified: Fri, 16 Feb 2007 13:38:18 UTC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php
/* Usage:
 * The first parameter is an array of the allowed languages. 
 * If no valid language is found, get_lang() returns false. 
 * If you set the second parameter to false, all language names stay as they are 
 * in the accept-language header.
 * If it is set to true (default behaviour) only the first part of the name is used:
 * de-de becomes de, ja-jp ja and so on.
 * 
 * Example:
 * get_lang(array('de', 'en', 'ja'), true);
 */
function get_lang($accepted_langs, $clean = true) {	
	$arr_lang = explode(",", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
	
	foreach($arr_lang as $lang) {
		$name = (($pos = strpos($lang, ";")) === false) ? $lang : 
			substr($lang, 0, $pos);
			
		if($clean === true) {
			$name = (($pos = strpos($name, "-")) === false) ? $name :
				substr($name, 0, $pos);
		}
			
		if(($pos = strpos($lang, "q=")) !== false) {
			$quality = (float)substr($lang, $pos+2, 4);
		}
		else {
			$quality = 1.0;
		}
		
		if(!isset($langs[$name]) or $langs[$name] < $quality) {
			$langs[$name] = $quality;
		}
	}
	
	arsort($langs);
	reset($langs);
	
	foreach($langs as $lang => $quality) {
		if(in_array($lang, $accepted_langs)) {
			return $lang;
		}
	}
	
	return false;
}
?>