从任何编码强制字符串为UTF-8

Hay*_*ian 37 ruby ruby-on-rails utf-8 character-encoding

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

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

kwa*_*ick 58

Ruby 1.9

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

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

str.encoding.name # => 'UTF-8'
Run Code Online (Sandbox Code Playgroud)

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

begin
  str.encode("UTF-8")
rescue Encoding::UndefinedConversionError
  # ...
end
Run Code Online (Sandbox Code Playgroud)

我肯定会阅读以下帖子以获取更多信息:http:
//graysoftinc.com/character-encodings/ruby-19s-string


Joh*_*ard 29

这将确保您具有正确的编码并且不会出错,因为它用空字符串替换任何无效或未定义的字符.

无论如何,这都将确保您拥有有效的UTF-8字符串

str.encode(Encoding.find('UTF-8'), {invalid: :replace, undef: :replace, replace: ''})
Run Code Online (Sandbox Code Playgroud)

  • 这将在现代 ruby​​ 上引发 `noimplicit conversion of Hash into String`(可能在 3.0 之后)使用 `str.encode(Encoding.find('UTF-8'), invalid: :replace, undef: :replace, Replace: ' ')` (3认同)

ar3*_*1an 5

只有这个解决方案对我有用:

string.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
Run Code Online (Sandbox Code Playgroud)

注意二进制参数。