Help us understand the problem. What is going on with this article?

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)
}
suin
Qiita 4位/TypeScript入門書執筆中/TypeScripterのための座談会「YYTypeScript」主催/『実践ドメイン駆動設計』書籍邦訳レビュア/分報Slack考案/YYPHP主催/CodeIQマガジン執筆/株式会社クラフトマンソフトウェア創設/Web自動テスト「ShouldBee」の開発/TypeScript/DDD/OOP
https://yyts.connpass.com/
shouldbee
開発者向けテスト支援サービスShouldBeeを開発・運営するスタートアップ(onlab第8期)
http://shouldbee.at
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした