Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove 4 byte utf-8 characters in Ruby?

Since MySQL's utf8 doesn't support 4 byte characters, I'm looking for a way to detect and eliminate any 4 byte utf8 characters from a string in Ruby. I understand that I can update my table to use utf8m4 but for a couple reasons that's not possible or the desired solution.

Simply encoding the string to ASCII will remove these characters but will also remove all other non-ASCII characters, which is not good.

like image 582
JZC Avatar asked May 10 '13 17:05

JZC


2 Answers

The following seems to work for me in Ruby 1.9.3:

input.each_char.select{|c| c.bytes.count < 4 }.join('')

For example:

input = "hello \xF0\xA9\xB6\x98 world"                  # includes U+29D98
input.each_char.select{|c| c.bytes.count < 4 }.join('') # 'hello  world'
like image 154
John Ledbetter Avatar answered Oct 09 '22 16:10

John Ledbetter


Another option (tested in ruby 2.7) is to use a regular expression with gsub:

input = "hello \xF0\xA9\xB6\x98 world"    # includes U+29D98
input.gsub(/[\u{10000}-\u{10FFFF}]/, "?") # 'hello ? world'
like image 32
James Healy Avatar answered Oct 09 '22 15:10

James Healy