Search code examples
phpstringcomparisoncomparestring-comparison

Is there a way to compare two strings in Spanish regardless of the accents in PHP?


My question is, given i have the following php code to compare two strings:

   $cadena1='JUAN LÓPEZ YÁÑEZ';
   $cadena2='JUAN LOPEZ YÁÑEZ';

   if($cadena1===$cadena2){
     echo '<p style="color: green;">The strings match!</p>';
   }else{
     echo '<p style="color: red;">The strings do not match. Accent sensitive?</p>';
   }

I notice for example that if I compare LOPEZ and LÓPEZ then the comparison turns to false.

Is there a way or a function already there to compare these strings regardless of the Spanish accents?


Solution

  • I would replace all accents in your strings before comparing them. You can do that using the following code:

    $replacements = array('Ó'=>'O', 'Á'=>'A', 'Ñ' => 'N'); //Add the remaining Spanish accents. 
    $output = strtr("JUAN LÓPEZ YÁÑEZ",$replacements);
    

    output will now be equal to cadena2.