Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP case and accent insensitive search into an array

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?

like image 368
FidoBoy Avatar asked Feb 25 '23 19:02

FidoBoy


2 Answers

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

like image 136
Naftali Avatar answered Mar 04 '23 05:03

Naftali


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

like image 35
dynamic Avatar answered Mar 04 '23 04:03

dynamic