how to replace special characters with the ones they're based on in PHP?

Carlos picture Carlos · Dec 11, 2009 · Viewed 66.5k times · Source

How do I replace:

  • "ã" with "a"
  • "é" with "e"

in PHP? Is this possible? I've read somewhere I could do some math with the ascii value of the base character and the ascii value of the accent, but I can't find any references now.

Answer

Alix Axel picture Alix Axel · Dec 11, 2009

If you don't have access to the Normalizer class or just don't wish to use it you can use the following function to replace most (all?) of the common accentuations.

function Unaccent($string)
{
    return preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8'));
}