Created
March 18, 2015 05:06
-
-
Save artoodetoo/9c98a3c4fabac13e4f32 to your computer and use it in GitHub Desktop.
Internationalization functions: user preffered language and translate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function userLanguage(array $preferred = ['en', 'ru']) | |
{ | |
static $language; | |
// calculate preferred language and do it only once | |
if (!isset($language)) { | |
$language = $preferred[0]; | |
// user has choosen the language | |
if (isset($_COOKIE['lang']) && in_array($_COOKIE['lang'], $preferred)) { | |
$language = $_COOKIE['lang']; | |
// the language are set in browser settings | |
// for ex. Accept-Language=en-ca,en;q=0.8,en-us;q=0.6,de;q=0.2 | |
} elseif (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'], | |
$matches | |
)) { | |
$langs = array_combine($matches[1], $matches[4]); | |
foreach ($langs as $lang => $val) { | |
if ($val === '') { | |
$langs[$lang] = 1; | |
} | |
} | |
arsort($langs, SORT_NUMERIC); | |
$intersect = array_intersect(array_keys($langs), $preferred); | |
if (reset($intersect)) { | |
$language = current($intersect); | |
} | |
} | |
} | |
return $language; | |
} | |
function t($str) | |
{ | |
static $phrases; | |
// get language + dictionary and do it only once | |
if (!isset($phrases)) { | |
$lang = userLanguage(); | |
$filename = __DIR__."/i18n/{$lang}.php"; | |
$phrases = file_exists($filename) ? include($filename) : []; | |
} | |
// get translation or original phrase | |
return isset($phrases[$str]) ? $phrases[$str] : $str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example: