简体   繁体   English

在Ruby中只删除字符串中的表情符号

[英]Remove only emoticons from string in Ruby

A user is using an emoticon and it is erroring out my app. 用户正在使用表情符号,这是错误的我的应用程序。 How can I get check if the string contains an emoticon and remove only the emoticon? 如何检查字符串是否包含表情符号并仅删除表情符号?

 Message.create(user: @user, ticket: @ticket, text: "\r\nIm done with this bug! \u{1f431}!\r\n")

 ActiveRecord::StatementInvalid: Mysql2::Error: Incorrect string value: 'x90\xB1!\x0D

This is occuring because your database doesnt allow for utf8mb4 so you need to check for both and return the text. 这是因为您的数据库不允许使用utf8mb4,因此您需要检查两者并返回文本。 I would do the check as a callback and only if the text field has changed in order to reduce the number of times the callback is called. 我会将检查作为回调进行,并且只有在文本字段发生变化时才会减少调用回调的次数。

 before_save :ensure_utf8, if: :text_changed?

def ensure_utf8
   if self.text
      self.text = self.text.encode( Encoding.find('UTF-8'), { invalid: :replace, undef: :replace, replace: '' } )
      self.text = self.text.each_char.select { |c| c.bytes.first < 240 }.join('')
   end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM