Home >Backend Development >PHP Tutorial >How can I convert non-Latin characters to ASCII equivalents in PHP?

How can I convert non-Latin characters to ASCII equivalents in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 05:44:301052browse

How can I convert non-Latin characters to ASCII equivalents in PHP?

PHP Foreign Character Removal

For situations where URLs and other user-facing content must be devoid of non-Latin characters, finding a solution to convert these characters to their ASCII equivalents becomes essential. Despite extensive online research, finding a comprehensive list or solution has proven to be a challenge.

Solution: Transliteration Using Iconv

Iconv, a versatile library for character conversion, provides a solution tailored to this specific need through its transliteration encoding capability. By appending "//"TRANSLIT" to the target character set during conversion, iconv attempts to approximate any unrepresentable characters with visually similar Latin characters.

Example

<code class="php"><?php
// Define the original string containing non-Latin characters
$foreignString = 'אבגדהוזחטיכלמנסעפצקרשת';

// Perform transliteration using iconv
$latinString = iconv('UTF-8', 'ASCII//TRANSLIT', $foreignString);

// Print the transliterated string with only ASCII characters
echo $latinString; // Output: AbgdHzHtyklmnSpFqkRSt
?></code>

This solution effectively removes all foreign characters from the input string, ensuring that URLs and other content meet the required ASCII-only restriction.

The above is the detailed content of How can I convert non-Latin characters to ASCII 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