Home  >  Article  >  Backend Development  >  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
Mary-Kate OlsenOriginal
2024-10-30 17:54:03926browse

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>

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>

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>

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!

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