Home > Backend Development > PHP Tutorial > How to Replace Special Characters with Their Base Equivalents in PHP?

How to Replace Special Characters with Their Base Equivalents in PHP?

Mary-Kate Olsen
Release: 2024-10-30 17:54:03
Original
1032 people have browsed it

How to Replace Special Characters with Their Base Equivalents in PHP?

Replacing Special Characters with Their Base Equivalents in PHP

Question: Is it possible to replace special characters with their base equivalents in PHP, such as converting "ã" to "a" and "é" to "e"?

Answer: Yes, it is possible to replace accented characters with their base equivalents using PHP.

Method:

If you have access to the Normalizer class, you can use the Normalizer::normalize() method with the Normalizer::FORM_D constant:

<code class="php">$string = "ãé";
$baseString = Normalizer::normalize($string, Normalizer::FORM_D);</code>
Copy after login

If you don't have access to the Normalizer class, you can use the following function:

<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 converts HTML entities to their corresponding characters and then removes common accent marks using regular expressions.

Example:

<code class="php">$string = "ãé";
$baseString = Unaccent($string);</code>
Copy after login

The resulting $baseString variable will contain "ae".

The above is the detailed content of How to Replace Special Characters with Their 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