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.
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'
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With