How to re-create a URL with Accept-Language + split?

1

I am having a code in PHP , it informs the browser language and returns with a redirect .

Code

<?php
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
header("Location: http://meusite.com/$lang" ) ;
?>

It redirects to:

meusite.com/pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4

The right one would be to redirect to meusite.com/pt-BR because my browser has the language pt-BR .

Will creating a split solve?

The member Maia did so:

$lang = split(",", $_SERVER['HTTP_ACCEPT_LANGUAGE'])[0];

In case the URL would only go to the first comma, leaving only: meusite.com/pt-BR . But the code seems to be wrong, does not work.

I would like to do this with the URL, leaving up /pt-BR , or even leaving it:

meusite.com/pt

The member suggested that I change the index from [0] to 1 thus leaving:

$lang = split(",", $_SERVER['HTTP_ACCEPT_LANGUAGE'])[1];

It just does not work, so I would like some example of how to redirect it to / en-US or how to redirect to / en

    
asked by anonymous 30.06.2014 / 06:12

1 answer

4

A quick solution 1 follows:

<?php

$langs = array();
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {

   // Cá entre nós, usar regex pra isso é forçar a amizade, mas lá vai :)
   preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse);

   //Aqui vamos ordenar por preferência do usuário
   if (count($lang_parse[1])) {
      $langs = array_combine($lang_parse[1], $lang_parse[4]);
      foreach ($langs as $lang => $val) {
         if ($val === '') $langs[$lang] = 1;
      }
      arsort($langs, SORT_NUMERIC);
   }
}

// Aqui você põe apenas as linguagens que seu site REALMENTE tem:
foreach ($langs as $lang => $val) {
   if ( strpos($lang, 'pt') === 0) {
      header( "Location: http://meusite.com/pt/" ) ;
      exit();
   } else if (strpos($lang, 'en') === 0) {
      header( "Location: http://meusite.com/en/" ) ;
      exit();
   } 
}
// Se nao achar nenhuma:
header( "Location: http://meusite.com/pt/" ) ;
exit();

?>

You do not need to pt-BR , nor en-US , unless you want to separate pt-BR from pt-PT , and so on.

1. searched the Duck Duck Go, running.

Source: link

    
30.06.2014 / 06:40