在 Ruby 中将所有非 ASCII 字符替换为其 ASCII 等效字符的最简单方法是什么?
Possible Duplicate:
Transliteration in ruby
I am searching for a simple way to convert strings like these:
- "spaß" to "spass"
- "über" to "ueber"
- etc.
This is needed for generating valid usernames from names of people.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这称为音译。可以使用 Iconv 类。
尝试以下操作之一(首先需要“iconv”):
还有一个
iconv
命令行实用程序。有关该内容和一些 Ruby 示例的更多信息(搜索“ruby”)此处。另一种方法是 Unidecode< /a>,我猜这是受到原始 Perl 实现的启发。我还没有在 Ruby 版本中使用过它,但它应该可以更好地进行多字符扩展(这显然是您想要的)。
最后,如果您正在运行 Rails,您可能会找到此线程 有趣。它详细介绍了替代音译方法之间的一些差异,并展示了在 Rails 核心内执行此操作的方法 (
ActiveSupport::Inflector.transliterate
)This is called transliteration. An approximation of this (see examples) can be performed using the Iconv class.
Try one of the following (require 'iconv' first):
There's also an
iconv
command line utility. More information on that and some Ruby examples (search for 'ruby') here.An alternative to this is Unidecode, which I guess was inspired by the original Perl implementation. I haven't used it in its Ruby incarnation, but it should do multi-char expansions (which apparently you want) better.
Finally, if you're running Rails, you may find this thread interesting. It details some differences between alternative approaches to transliteration, and shows a way to do this within the Rails core (
ActiveSupport::Inflector.transliterate
)