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

Mary-Kate Olsen
Release: 2024-11-01 07:44:02
Original
204 people have browsed it

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!