"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How can I convert non-ASCII characters to ASCII equivalents in PHP?

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

Published on 2024-11-18
Browse:909

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

PHP Transliteration

Q: Can I convert non-ASCII characters to their ASCII equivalents in PHP?

A: Yes, you can use the iconv function with the transliteration encoding to do this.

The transliteration encoding in iconv allows you to approximate non-ASCII characters using similar-looking ASCII characters. This is useful for generating URLs that contain only ASCII characters.

Here's an example of how to use iconv with transliteration:

$string = "こんにちは";
$result = iconv("UTF-8", "ASCII//TRANSLIT", $string);
echo $result; // Output: konnichiwa

In this example, the UTF-8 encoded string is converted to ASCII using transliteration. The resulting string contains only ASCII characters and still resembles the original string.

Here's a complete example that matches your use case of displaying ASCII-only URLs:

$url = "https://example.com/にほんご";
$asciiUrl = iconv("UTF-8", "ASCII//TRANSLIT", $url);
echo "Visit our website";

This will generate a URL that contains only ASCII characters and will still redirect users to the intended page.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3