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>
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>
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!