PHP case and accent-insensitive array search

I have an array containing words, some of them with accents. I want to check if a given word is included in this array, but makes it random and accentuating. For instance:

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

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

Any ideas?

+4
source share
4 answers

Try this :: - 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; } 

to use it:

 check_array($array, 'Camion'); 

using strcasecmp as suggested by Felix Kling

+4
source

You must use iconv with TRANSLIT

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

But consider an iconv TRANSLIT based on SO. Thus, the results do not match the machine and the machine.

After normalizing accents, you can do strtolower () or do a search using REGEX / i

+2
source

The easiest way is to set up the translation table as follows:

 $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 translate in byte order:

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

after which everything should be in the English az AZ range.

If your server supports iconv , you can do something like this:

 $string = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $string); 
+1
source

See subscript substring without accents for a similar question and some ideas on how to do this.

0
source

Source: https://habr.com/ru/post/1343974/


All Articles