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

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

Patricia Arquette
Release: 2024-11-02 19:44:30
Original
909 people have browsed it

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:

<code class="php">$string = "こんにちは";
$result = iconv("UTF-8", "ASCII//TRANSLIT", $string);
echo $result; // Output: konnichiwa</code>
Copy after login

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:

<code class="php">$url = "https://example.com/にほんご";
$asciiUrl = iconv("UTF-8", "ASCII//TRANSLIT", $url);
echo "<a href='$asciiUrl'>Visit our website</a>";</code>
Copy after login

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

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