Detect Browser Language in PHP

后端 未结 13 1372
孤城傲影
孤城傲影 2020-11-22 09:16

I use the following PHP script as index for my website.

This script should include a specific page depending on the browser\'s language (automatically detected).

13条回答
  •  独厮守ぢ
    2020-11-22 09:37

    All of the above with fallback to 'en':

    $lang = substr(explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE'])[0],0,2)?:'en';
    

    ...or with default language fallback and known language array:

    function lang( $l = ['en'], $u ){
        return $l[
            array_keys(
                $l,
                substr(
                    explode(
                        ',',
                        $u ?: $_SERVER['HTTP_ACCEPT_LANGUAGE']
                    )[0],
                    0,
                    2
                )
            )[0]
        ] ?: $l[0];
    }
    

    One Line:

    function lang($l=['en'],$u){return $l[array_keys($l,substr(explode(',',$u?:$_SERVER['HTTP_ACCEPT_LANGUAGE'])[0],0,2))[0]]?:$l[0];}
    

    Examples:

    // first known lang is always default
    $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'en-us';
    lang(['de']); // 'de'
    lang(['de','en']); // 'en'
    
    // manual set accept-language
    lang(['de'],'en-us'); // 'de'
    lang(['de'],'de-de, en-us'); // 'de'
    lang(['en','fr'],'de-de, en-us'); // 'en'
    lang(['en','fr'],'fr-fr, en-us'); // 'fr'
    lang(['de','en'],'fr-fr, en-us'); // 'de'
    

提交回复
热议问题