How to match browser localization with one of my php gettext i18n?

I started using gettext to translate my site. So far, I have translated key menus and headings into French, Spanish, and Portuguese.

My folder structure is as follows:

.../locale
    /en_GB.utf8
        /LC_MESSAGES
            messages.po
            messages.mo
    /fr_FR.utf8
        /LC_MESSAGES
            messages.po
            messages.mo
    /es_ES.utf8
        /LC_MESSAGES
            messages.po
            messages.mo
    /pt_PT.utf8
        /LC_MESSAGES
            messages.po
            messages.mo

I can get the user's default local browser:

$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);

If their locale en_GB, fr_FR, es_ESor pt_PT, it works fine, I'll just add a locale .utf8, and I feel good to go.

But the language standard cannot be set at all. Hmm, ok, so add the following:

if (!$locale) {
    $locale = 'en_GB';
}

But I know that language can be simple fr(and perhaps fr?). No problem, this will catch most of them:

if (strlen($locale)==2) {
    $locale = strtolower($locale).'_'.strtoupper($locale);
}

, . , , , -, french . , , , .

?

, , Locale::lookup , , , :

var_dump(Locale::lookup(['en_GB','fr_FR','es_ES','pt_PT'], 'fr'));     // ''
var_dump(Locale::lookup(['en_GB','fr_FR','es_ES','pt_PT'], 'fr_FR'));  // 'fr_FR'
var_dump(Locale::lookup(['en_GB','fr_FR','es_ES','pt_PT'], 'fr_CA'));  // ''
var_dump(Locale::lookup(['en_GB','fr_FR','es_ES','pt_PT'], 'french')); // ''

var_dump(Locale::lookup(['en','fr','es','pt'], 'fr'));                 // 'fr'
var_dump(Locale::lookup(['en','fr','es','pt'], 'fr_FR'));              // 'fr'
var_dump(Locale::lookup(['en','fr','es','pt'], 'fr_CA'));              // 'fr'
var_dump(Locale::lookup(['en','fr','es','pt'], 'french'));             // ''
+4

Source: https://habr.com/ru/post/1618138/


All Articles