Error removing accents from a string for creating friendly URLs

2

Hello, I would like to know how I can get around the error that is being caused in the code below. When I add accents, special characters are being dropped instead of converted.

I got this code with a friend for a while and nothing started to present this error on several hosting hosts I do not know if it was because of the PHP update but in any case I would like to know why you are presenting this error .

The error is literally taking special characters and accents and putting in their place the value of the variable $slug , that is, if the value of $slug is a dash, it draws accents and special characters and traces them in the place instead of convert.

Example working before:

Testing text conversion to friendly URL 1 = Testing-text-to-url-friend-friendly-conversion

Action, Comedy = action-comedy

Example of the current error:

Testing text-to-url-friendly URL conversion 1 = test-converting-text-to-url-friendly-1

Action, Comedy = the-comedy

Literally the characters that were being converted are being deleted how can I fix this?

   function removeAcentos($string, $slug = false) {
      $string = strtolower($string);

      // Código ASCII das vogais
      $ascii['a'] = range(224, 230);
      $ascii['e'] = range(232, 235);
      $ascii['i'] = range(236, 239);
      $ascii['o'] = array_merge(range(242, 246), array(240, 248));
      $ascii['u'] = range(249, 252);

      // Código ASCII dos outros caracteres
      $ascii['b'] = array(223);
      $ascii['c'] = array(231);
      $ascii['d'] = array(208);
      $ascii['n'] = array(241);
      $ascii['y'] = array(253, 255);

      foreach ($ascii as $key=>$item) {
        $acentos = '';
        foreach ($item AS $codigo) $acentos .= chr($codigo);
        $troca[$key] = '/['.$acentos.']/i';
      }

      $string = preg_replace(array_values($troca), array_keys($troca), $string);

      // Slug?
      if ($slug) {
        // Troca tudo que não for letra ou número por um caractere ($slug)
        $string = preg_replace('/[^a-z0-9]/i', $slug, $string);
        // Tira os caracteres ($slug) repetidos
        $string = preg_replace('/' . $slug . '{2,}/i', $slug, $string);
        $string = trim($string, $slug);
      }

      return $string;
    }
echo removeAcentos(Ação, Comédia, Ficção Cientifica, '-');

Code sample working to show error click here

    
asked by anonymous 03.10.2015 / 18:58

1 answer

5

Do you just want to convert accents to common letters?

Use the iconv function.

So do this:

echo iconv('utf-8', 'us-ascii//TRANSLIT', 'Pêra maçã côco'); 

Output:

  

Coconut maca pear

See working at IDEONE

    
03.10.2015 / 19:06