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

How to Convert Accented Characters to Base Equivalents in PHP?

Mary-Kate Olsen
Release: 2024-10-30 15:44:26
Original
954 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template