从任何编码强制字符串到UTF-8 [英] Force strings to UTF-8 from any encoding

查看:589
本文介绍了从任何编码强制字符串到UTF-8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的rails应用程序,我使用来自世界各地的RSS feed,一些feed有不是UTF-8的链接。原始Feed链接不受我的控制,为了在应用的其他部分使用它们,他们需要使用UTF-8。

In my rails app I'm working with RSS feeds from all around the world, and some feeds have links that are not in UTF-8. The original feed links are out of my control, and in order to use them in other parts of the app, they need to be in UTF-8.

我如何检测编码并转换为UTF-8?

How can I detect encoding and convert to UTF-8?

推荐答案

Ruby 1.9

强制编码很容易,但它不会转换字符只是更改编码

"Forcing" an encoding is easy, however it won't convert the characters just change the Encoding:

str = str.force_encoding("UTF-8")

str.encoding.name # => 'UTF-8'

如果要执行转换,请使用 encode

If you want to perform a converstion, use encode:

begin
  str.encode("UTF-8")
rescue Encoding::UndefinedConversionError
  # ...
end



请阅读以下信息获取更多信息:

http://graysoftinc.com/character- encodings / ruby​​-19s-string

这篇关于从任何编码强制字符串到UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆