将变音符号替换为“等效”字符PHP 中的 ASCII 码?
相关问题:
正如上面的问题,我正在寻找一种可靠、稳健的方法来使用 PHP 将任何 unicode 字符减少为接近等效的 ASCII。我真的想避免滚动我自己的查找表。
例如(从第一个引用的问题中窃取):Gračišće
变为 Gracisce
Related questions:
- How to replace characters in a java String?
- How to replace special characters with their equivalent (such as " á " for " a") in C#?
As in the questions above, I'm looking for a reliable, robust way to reduce any unicode character to near-equivalent ASCII using PHP. I really want to avoid rolling my own look up table.
For example (stolen from 1st referenced question): Gračišće
becomes Gracisce
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
iconv 模块可以做到这一点,更具体地说,iconv() 函数:
iconv 的主要麻烦是你只需要观察你的编码,但这绝对是正确的完成这项工作的工具(由于我使用的文本编辑器的限制,我使用“Windows-1252”作为示例;)您肯定想要使用的 iconv 功能是
//TRANSLIT
标志,它告诉 iconv 将任何没有 ASCII 匹配的字符音译为最接近的近似值。The iconv module can do this, more specifically, the iconv() function:
The main hassle with iconv is that you just have to watch your encodings, but it's definitely the right tool for the job (I used 'Windows-1252' for the example due to limitations of the text editor I was working with ;) The feature of iconv that you definitely want to use is the
//TRANSLIT
flag, which tells iconv to transliterate any characters that don't have an ASCII match into the closest approximation.我根据@zombat 的答案找到了另一个解决方案。
他的回答的问题是我得到:
从函数中删除
//IGNORE
后,我得到:因此,
š
字符被正确翻译,但另一个角色不是。对我有用的解决方案是
preg_replace
(删除除 [a-zA-Z0-9] 之外的所有内容 - 包括空格)和 @zombat 的解决方案:输出:
I found another solution, based on @zombat's answer.
The issue with his answer was that I was getting:
And after removing
//IGNORE
from the function, I got:So, the
š
character was translated correctly, but the other characters weren't.The solution that worked for me is a mix between
preg_replace
(to remove everything but [a-zA-Z0-9] - including spaces) and @zombat's solution:Output:
我的解决方案是创建两个字符串 - 第一个包含不需要的字母,第二个包含将替换第一个的字母。
My solution is to create two strings - first with not wanted letters and second with letters that will replace firsts.
试试这个:
根据此线程中选定的答案:PHP 中的 URL 友好用户名?
Try this:
Based on the selected answer in this thread: URL Friendly Username in PHP?
你也应该尝试:
我从这里找到了这个:
https://www.php.net/manual/en/transliterator。音译.php#111939
You should also try:
I found this from here:
https://www.php.net/manual/en/transliterator.transliterate.php#111939