4

I have an array containing words, some of them with accents. I want to test if a given word is into that array but making it case and accent insensitive. For example:

$array = array("coche","camión","moto","carro");

i want a simple little function, something like in_array. If my string is 'Camion' or 'camión' it should return true.

Any ideas?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
FidoBoy
  • 392
  • 6
  • 18

3 Answers3

5

Try this out: :-D

function check_array($array, $string){
   $trans = array("é" => "e", "é" => "e", "á" => "a", "á" => "a", "í" => "i","í"=>"i", "ó"=>"o", "ó" => "o", "ú" => "u", "ú"=>"u","ö" => "u", "ü"=>"u");
   $realString = strtr($string,$trans);
   foreach($array as $val){
      $realVal = strtr($val,$trans);
      if(strcasecmp( $realVal, $realString ) == 0){
         return true;
      }
   }
   return false;
}

so to use it:

check_array($array, 'Camion');

using strcasecmp as per Felix Kling suggestion

Community
  • 1
  • 1
Naftali
  • 144,921
  • 39
  • 244
  • 303
2

You should use iconv with TRANSLIT

http://php.net/manual/en/function.iconv.php

But consider the iconv TRANSLIT is SO based. So the results aren't the same from machine to machine.

After you have normalized accents you can do a strtolower() or a search with REGEX /i

dynamic
  • 46,985
  • 55
  • 154
  • 231
1

The simplest way is to set up a translation table like so:

$translation = array(
    'from' => array(
        'à','á','â','ã','ä', 'ç', 'è','é','ê','ë', 'ì','í','î','ï', 'ñ',
        'ò','ó','ô','õ','ö', 'ù','ú','û','ü', 'ý','ÿ', 'À','Á','Â','Ã',
        'Ä','Ç', 'È','É','Ê','Ë', 'Ì','Í','Î','Ï', 'Ñ', 'Ò','Ó','Ô','Õ',
        'Ö', 'Ù','Ú','Û','Ü', 'Ý')
    'to' => array(
        'a','a','a','a','a', 'c', 'e','e','e','e', 'i','i','i','i', 'n',
        'o','o','o','o','o', 'u','u','u','u', 'y','y', 'A','A','A','A','A',
        'C','E','E','E','E', 'I','I','I','I', 'N', 'O','O','O','O','O',
        'U','U','U','U', 'Y')
);

and then you can use strtr to do a translate in byte order:

$string = strtr("Camion",$translation['from'],$translation['to']);

following that it should all be in the English range a-z A-Z.

If your server supports iconv you can do something like so:

$string = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $string);
RobertPitt
  • 56,863
  • 21
  • 114
  • 161