3v4l.org

run code in 500+ PHP versions simultaneously
<?php function detectLanguage(array $langs, string $header): ?string { $s = strtolower($header); // case insensitive $s = strtr($s, '_', '-'); // cs_CZ means cs-CZ rsort($langs); // first more specific preg_match_all('#(' . implode('|', $langs) . ')(?:-[^\s,;=]+)?\s*(?:;\s*q=([0-9.]+))?#', $s, $matches); if (!$matches[0]) { return null; } $max = 0; $lang = null; foreach ($matches[1] as $key => $value) { $q = $matches[2][$key] === '' ? 1.0 : (float) $matches[2][$key]; if ($q > $max) { $max = $q; $lang = $value; } } return $lang; } echo detectLanguage(['en', 'fr', 'zn'], 'cs,en;q=0.9,fr;q=0.8,zh-CN;q=0.7,zh;q=0.6');
Output for 8.1.34, 8.2.0 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.18, 8.5.0 - 8.5.3
en

preferences:
57.52 ms | 832 KiB | 4 Q