Ruby: Escaping special characters in a string

帅比萌擦擦* 提交于 2019-12-10 02:28:57

问题


I am trying to write a method that is the same as mysqli_real_escape_string in PHP. It takes a string and escapes any 'dangerous' characters. I have looked for a method that will do this for me but I cannot find one. So I am trying to write one on my own.

This is what I have so far (I tested the pattern at Rubular.com and it worked):

# Finds the following characters and escapes them by preceding them with a backslash. Characters: ' " . * / \ -
def escape_characters_in_string(string)
  pattern = %r{ (\'|\"|\.|\*|\/|\-|\\) }
  string.gsub(pattern, '\\\0') # <-- Trying to take the currently found match and add a \ before it I have no idea how to do that).
end

And I am using start_string as the string I want to change, and correct_string as what I want start_string to turn into:

start_string = %("My" 'name' *is* -john- .doe. /ok?/ C:\\Drive)
correct_string = %(\"My\" \'name\' \*is\* \-john\- \.doe\. \/ok?\/ C:\\\\Drive)

Can somebody try and help me determine why I am not getting my desired output (correct_string) or tell me where I can find a method that does this, or even better tell me both? Thanks a lot!


回答1:


Your pattern isn't defined correctly in your example. This is as close as I can get to your desired output.

Output

"\\\"My\\\" \\'name\\' \\*is\\* \\-john\\- \\.doe\\. \\/ok?\\/ C:\\\\Drive"

It's going to take some tweaking on your part to get it 100% but at least you can see your pattern in action now.

  def self.escape_characters_in_string(string)
    pattern = /(\'|\"|\.|\*|\/|\-|\\)/
    string.gsub(pattern){|match|"\\"  + match} # <-- Trying to take the currently found match and add a \ before it I have no idea how to do that).
  end



回答2:


I have changed above function like this:

  def self.escape_characters_in_string(string)
    pattern = /(\'|\"|\.|\*|\/|\-|\\|\)|\$|\+|\(|\^|\?|\!|\~|\`)/
    string.gsub(pattern){|match|"\\"  + match}
  end

This is working great for regex




回答3:


This should get you started:

print %("'*-.).gsub(/["'*.-]/){ |s| '\\' + s }
\"\'\*\-\.



回答4:


Take a look at the ActiveRecord sanitization methods: http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-sanitize_sql_array




回答5:


Take a look at escape_string / quote method in Mysql class here



来源:https://stackoverflow.com/questions/4140582/ruby-escaping-special-characters-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!