Home > Article > Backend Development > How to Replace Special Characters with Their Base Characters in PHP?
Replacing Special Characters in PHP
How do you replace special characters with their base characters in PHP? For instance, "ã" with "a" and "é" with "e".
Solution:
One way to achieve this is through the Normalizer class.
For example, to replace "ã" with "a" and "é" with "e":
<code class="php">use Normalizer; $string = "Thãe"; // Replace "ã" with "a" and "é" with "e" $replacedString = Normalizer::normalize($string, Normalizer::FORM_D); echo $replacedString; // Output: "The"</code>
However, if you do not have access to the Normalizer class or prefer a different approach, you can use the following function:
<code class="php">function Unaccent($string) { return preg_replace('~&([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 handles most common accentuation characters by replacing them with their base equivalents.
The above is the detailed content of How to Replace Special Characters with Their Base Characters in PHP?. For more information, please follow other related articles on the PHP Chinese website!