php get lang by accept-lang


    private function getLang(): string
    {
        $supported = ['de', 'en'];

        // "ru-RU,ru;q=0.9,en-US;q=0.8" → ["ru-RU", "ru;q=0.9", "en-US;q=0.8"]
        $parts = explode(',', request()->header('accept-language', ''));

        $best = null;
        $bestQ = -1;

        foreach ($parts as $part) {
            $part = trim($part);
            $code = strtolower(substr($part, 0, 2));
            $q = str_contains($part, ';q=') ? (float) substr($part, strpos($part, ';q=') + 3) : 1.0;

            if ($q > $bestQ && in_array($code, $supported)) {
                $best = $code;
                $bestQ = $q;
            }
        }

        return $best ?? 'en';
    }