0

I would like to replace some invalid characters, I have an array that contains the correspondences:

$map = array(
    "à" => "a",
    "è" => "e",
    "ì" => "i",
    "ò" => "o",
    "ù" => "u"
);

I wanted to use the function str_replace($pattern, $replacement, $string) but I can't come to a conclusion. How can I proceed?

mikelplhts
  • 1,181
  • 3
  • 11
  • 32

3 Answers3

0

How about using a for-loop to process each index of a String variable and applying the replace function for each?

theString = "whatever"
String[] = theString.split();

for(int i=0; i<String[].length; i++){
   char tmp  = String[i].toChar();

   if(map.containsKey(tmp)){
      char replace = map.getValue(tmp);
      tmp = replace;
      String[i] = tmp.toString();
   }

 }

Just helping you think it through, this code wont actually run.

0

Hope it helps

function sanitize($string) {
    $string = str_replace(
        array('á', 'à', 'ä', 'â', 'ª', 'Á', 'À', 'Â', 'Ä'),
        array('a', 'a', 'a', 'a', 'a', 'A', 'A', 'A', 'A'),
        $string
    );

    $string = str_replace(
        array('é', 'è', 'ë', 'ê', 'É', 'È', 'Ê', 'Ë'),
        array('e', 'e', 'e', 'e', 'E', 'E', 'E', 'E'),
        $string
    );

    $string = str_replace(
        array('í', 'ì', 'ï', 'î', 'Í', 'Ì', 'Ï', 'Î'),
        array('i', 'i', 'i', 'i', 'I', 'I', 'I', 'I'),
        $string
    );

    $string = str_replace(
        array('ó', 'ò', 'ö', 'ô', 'Ó', 'Ò', 'Ö', 'Ô'),
        array('o', 'o', 'o', 'o', 'O', 'O', 'O', 'O'),
        $string
    );

    $string = str_replace(
        array('ú', 'ù', 'ü', 'û', 'Ú', 'Ù', 'Û', 'Ü'),
        array('u', 'u', 'u', 'u', 'U', 'U', 'U', 'U'),
        $string
    );

    $string = str_replace(
        array('ñ', 'Ñ', 'ç', 'Ç'),
        array('n', 'N', 'c', 'C',),
        $string
    );


    return strtolower($string);
}
Eduardo Aguad
  • 811
  • 7
  • 15
0

The solution I've found is to use the function strtr(string $str, array $arr).

Having an array, like the one mentioned above:

$map = array(
    "à" => "a",
    "è" => "e",
    "ì" => "i",
    "ò" => "o",
    "ù" => "u"
);

I just do this:

$string = "àaaaàèììkkekeou";
$new_string = strtr($string, $map);

With the result: $new_string -> "aaaaaeiikkekeou"

For details on the function: strtr()

mikelplhts
  • 1,181
  • 3
  • 11
  • 32