获取PHP语言的默认语言环境 [英] Get default locale for language in PHP

查看:135
本文介绍了获取PHP语言的默认语言环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP后端,几种类型的设备可以通过公共API与之通信.请求通常包含响应所必需的语言(例如'en'或'fr'或'ru'等)-但不是完整的语言环境.在过去几年中,这对于我需要的一切都很好.但是,现在我需要在响应中包括日期信息,并且需要使用区域设置来格式化日期.

I have a PHP back-end to which several types of devices communicate via a public API. Requests normally contain a required language for the response (e.g. 'en' or 'fr' or 'ru', etc.) - but not the full locale. This has worked fine for everything I needed over the last couple of years. However now I need to include date information in the response - and need a locale to format dates.

如何从语言中获取语言环境?我确实知道,语言不足以唯一地标识语言环境,但是我至少需要一些东西.如果我可以获得至少一个语言环境,例如en_GB代表"en","ru_RU"代表"ru",等等-足够.

How can I get a locale from the language? I do understand that a language is not enough to uniquely identify a locale, but I need at least something. If I can get at least one locale, e.g. en_GB for 'en' or 'ru_RU' for 'ru', etc. - that would be sufficient.

推荐答案

考虑了更多有关该问题和我所拥有的特定设置之后,我想到了这种解决方案,该解决方案似乎可行.请注意,我无法控制需要支持的语言:将翻译文件放到预定义的位置,而系统语言环境则由其他人安装.在运行时,如果存在相应的翻译文件并且安装了系统区域设置,则需要支持一种特定的语言.这让我想到了这个解决方案:

Having thought more about the problem and the particular setup I have, I came up with this solution, which seems to work. Note that I don't have control over what languages I need to support: there are translation files dropped into a predefined place and system locales installed by someone else. During runtime, I need to support a particular language if corresponding translation file exists and and system locale is installed. This got me to this solution:

function getLocale($lang)
{
    $locs = array();
    exec('locale -a', $locs);

    $locale = 'en_GB';
    foreach($locs as $l)
    {
        $regex = "/$lang\_[A-Z]{2}$/";
        if(preg_match($regex, $l) && file_exists(TRANSROOT . "/$lang.php"))
        {
            $locale = $l;
            break;
        }
    }

    return $locale;
}

如果无法解析语言环境,则默认为en_GB,因为我确定已经安装了en_GB(我们和服务器一样位于英国).

I'm defaulting to en_GB if I cannot resolve a locale, because I know for certain that en_GB is installed (we're located in the UK as are our servers).

这篇关于获取PHP语言的默认语言环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆