Home  >  Article  >  Backend Development  >  How to Convert Accented Characters to Base Equivalents in PHP?

How to Convert Accented Characters to Base Equivalents in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-30 15:44:26854browse

How to Convert Accented Characters to Base Equivalents in PHP?

Replace Special Characters with Base Characters in PHP

The task is to convert accented characters to their base equivalents in PHP. For instance, "ã" should become "a" and "é" should become "e".

Solution:

While it's possible to perform mathematical operations on ASCII values, there are more straightforward methods.

Using the Normalizer Class:

PHP provides a Normalizer class that can simplify the process of character conversion. The following code demonstrates its usage:

<code class="php">use Normalizer;

$string = "ãé";
$base_string = Normalizer::normalize($string, Normalizer::FORM_D);</code>

Custom Function:

If the Normalizer class is unavailable, you can create a custom function to perform the replacement:

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

This function uses regular expressions to match and replace accented characters with their base equivalents.

Usage:

<code class="php">$string = "ãé";
$base_string = Unaccent($string);</code>

The above is the detailed content of How to Convert Accented Characters to Base Equivalents in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn