This article, will discuss multiple ways to remove accents from a string in PHP.
Table Of Contents
Background
Removing accents from a string is often required in web development, especially when dealing with internationalization, creating URL slugs, or processing user input. For instance, you might have a string like this:
$originalString = "Àçcèñted Têxt";
The goal is to convert it to a non-accented version:
"Accented Text"
This process involves replacing accented characters with their non-accented equivalents.
Solution 1: Using iconv()
The iconv() function in PHP is a powerful tool for character set conversion. You can use it to convert characters in a string to their ASCII equivalents, effectively removing accents.
Let’s see the complete example,
Frequently Asked:
- Remove a backslash from a String in PHP
- Remove the BOM (Byte Order Mark) from a String in PHP
- Remove a string after a comma in PHP
- Remove HTML tags from a String in PHP
<?php $originalString = "Àçcèñted Têxt"; // Set locale to handle characters correctly setlocale(LC_ALL, 'en_US.UTF8'); // Convert accented characters to ASCII $noAccentString = iconv('UTF-8', 'ASCII//TRANSLIT', $originalString); echo $noAccentString; ?>
Output
Accented Text
In this code:
– setlocale(LC_ALL, ‘en_US.UTF8’) sets the locale to handle characters properly in your environment.
– iconv(‘UTF-8’, ‘ASCII//TRANSLIT’, $originalString) converts the UTF-8 encoded $originalString to ASCII, transliterating characters to their closest ASCII equivalents.
– This method is generally reliable for removing accents from characters.
Solution 2: Using str_replace() and a Custom Mapping
If you prefer a more controlled approach or iconv() is not available in your environment, you can create a custom mapping of accented characters to their ASCII equivalents and use str_replace().
Let’s see the complete example,
<?php $originalString = "Àçcèñted Têxt"; // Mapping of accented characters to their ASCII equivalents $accents = ['À' => 'A', 'ç' => 'c', 'è' => 'e', 'ñ' => 'n', 'ê' => 'e']; $noAccentString = str_replace(array_keys($accents), array_values($accents), $originalString); echo $noAccentString; ?>
Output
Accented Text
In this code:
– $accents is an associative array mapping accented characters to their non-accented equivalents.
– str_replace(array_keys($accents), array_values($accents), $originalString) replaces each accented character in $originalString with its corresponding non-accented character.
– This method gives you full control over which characters are replaced and their replacements.
Summary
Removing accents from a string in PHP can be achieved using either iconv() for a broad transliteration approach or a custom mapping approach with str_replace() for more control. Both methods are effective for different scenarios and can be chosen based on the specific requirements of your string manipulation task.