我在PHP中这样做。接受语言是一件复杂的事情。浏览器可以建议它想要接受的多种语言(每种语言都有一个显示它更喜欢的品质因子)。
不幸的是,我的网站只有主要语言(EN,ES,FR)的翻译,而不是(en_US,en_GB,es_MX,es_ES),因此我选择了这些主要语言中指定的最高质量因子。
下面是一个未经测试的编辑,它应该从我的代码中删除大多数或所有依赖项。对不起,事情让我以前的答案感到困惑。我对我的函数进行了几次调用,并在其他地方进行了一些语言检查。下面的代码应该设置会话语言变量,您应该在其他地方使用它来确定正确的翻译。
它似乎比我以前的答案复杂得多,我不得不在我自己的代码中实现它。对于需要特定翻译(EN_US,EN_GB)的人,应修改以下代码以考虑preg_match_all中的匹配2。
$websiteLanguages = array('EN', 'ES');
session_start();
// The user wants a specific language regardless of their accept settings.
if (isset($_GET["lang"]))
{
$_SESSION["language"] = $_GET["lang"];
return;
}
// A language has already been decided upon.
if (isset($_SESSION["language"]))
{
return;
}
// No language has been chosen we should choose from the accept language.
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
{
// Parse the Accept-Language according to:
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
preg_match_all(
'/([a-z]{1,8})' . // M1 - First part of language e.g en
'(-[a-z]{1,8})*\s*' . // M2 -other parts of language e.g -us
// Optional quality factor M3 ;q=, M4 - Quality Factor
'(;\s*q\s*=\s*((1(\.0{0,3}))|(0(\.[0-9]{0,3}))))?/i',
$_SERVER['HTTP_ACCEPT_LANGUAGE'],
$langParse);
$langs = $langParse[1]; // M1 - First part of language
$quals = $langParse[4]; // M4 - Quality Factor
$numLanguages = count($langs);
$langArr = array();
for ($num = 0; $num < $numLanguages; $num++)
{
$newLang = strtoupper($langs[$num]);
$newQual = isset($quals[$num]) ?
(empty($quals[$num]) ? 1.0 : floatval($quals[$num])) : 0.0;
// Choose whether to upgrade or set the quality factor for the
// primary language.
$langArr[$newLang] = (isset($langArr[$newLang])) ?
max($langArr[$newLang], $newQual) : $newQual;
}
// sort list based on value
// langArr will now be an array like: array('EN' => 1, 'ES' => 0.5)
arsort($langArr, SORT_NUMERIC);
// The languages the client accepts in order of preference.
$acceptedLanguages = array_keys($langArr);
// Set the most preferred language that we have a translation for.
foreach ($acceptedLanguages as $preferredLanguage)
{
if (in_array($preferredLanguage, $websiteLanguages))
{
$_SESSION['Language'] = $preferredLanguage;
return;
}
}
}
// We will have returned by now if a language could be chosen, otherwise use
// our default language.
$_SESSION['Language'] = "EN";