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.
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;
}
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).