Skip to content

Instantly share code, notes, and snippets.

@rfay
Created June 25, 2012 04:50
Show Gist options
  • Save rfay/2986588 to your computer and use it in GitHub Desktop.
Save rfay/2986588 to your computer and use it in GitHub Desktop.
+/**
+ * Identify language from the Accept-language HTTP header we got.
+ * this is a simple copy from language_from_browser() in Drupal's language.inc.
+ * That one, unfortunately, discards any language that is not configured.
+ */
+function translatableregions_language_from_browser() {
+ // Specified by the user via the browser's Accept Language setting
+ // Samples: "hu, en-us;q=0.66, en;q=0.33", "hu,en-us;q=0.5"
+ $browser_langs = array();
+
+ if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
+ $browser_accept = explode(",", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
+ for ($i = 0; $i < count($browser_accept); $i++) {
+ // The language part is either a code or a code with a quality.
+ // We cannot do anything with a * code, so it is skipped.
+ // If the quality is missing, it is assumed to be 1 according to the RFC.
+ if (preg_match("!([a-z-]+)(;q=([0-9\\.]+))?!", trim($browser_accept[$i]), $found)) {
+ $browser_langs[$found[1]] = (isset($found[3]) ? (float) $found[3] : 1.0);
+ }
+ }
+ }
+
+ $language = 'en'; // Default language.
+ if (!empty($browser_langs)) {
+ // Order the codes by quality
+ arsort($browser_langs);
+ $language = key($browser_langs);
+ }
+ return $language;
+
+}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment