Is there a way in ruby 1.9 to remove invalid byte sequences from strings?

ε祈祈猫儿з 提交于 2019-11-28 07:19:59
Evgenii
"€foo\xA0".chars.select(&:valid_encoding?).join
Van der Hoorn
"€foo\xA0".encode('UTF-16le', invalid: :replace, replace: '').encode('UTF-8')

Ruby 2.0 and 1.9.3

"€foo\xA0".encode(Encoding::UTF_8, Encoding::UTF_8, :invalid => :replace)

Ruby 2.1+

"€foo\xA0".scrub
    data = '' if not (data.force_encoding("UTF-8").valid_encoding?)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!