PHP

HTTP_ACCEPT_LANGUAGEをパースする関数

More than 5 years have passed since last update.
<?php
$cases = array(
    'ja',
    'ja-jp',
    'ja;q=1',
    'da, en-gb;q=0.8, en;q=0.7',
);

foreach ( $cases as $case )
{
    $acceptLanguages = parse_accept_language($case);
    echo 'CASE: '.$case.PHP_EOL;
    var_dump($acceptLanguages);
}

function parse_accept_language($acceptLanguage)
{
    preg_match_all('/(?P<langcode>[a-z-]+)(?:;q=(?P<quality>[0-9\.]+))?/', $acceptLanguage, $matches);

    foreach ( $matches['quality'] as &$quality )
    {
        if ( $quality === '' )
        {
            $quality = 1.0;
        }
        else
        {
            $quality = floatval($quality);
        }
    }

    $acceptLanguages = array_combine($matches['langcode'], $matches['quality']);

    return $acceptLanguages;
}

結果

CASE: ja
array(1) {
  ["ja"]=>
  float(1)
}
CASE: ja-jp
array(1) {
  ["ja-jp"]=>
  float(1)
}
CASE: ja;q=1
array(1) {
  ["ja"]=>
  float(1)
}
CASE: da, en-gb;q=0.8, en;q=0.7
array(3) {
  ["da"]=>
  float(1)
  ["en-gb"]=>
  float(0.8)
  ["en"]=>
  float(0.7)
}