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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 07:44:02302browse

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('~&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 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!

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