Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Escaping special characters in a string

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!

like image 656
ab217 Avatar asked Nov 10 '10 01:11

ab217


2 Answers

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
like image 61
rwilliams Avatar answered Sep 18 '22 12:09

rwilliams


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

like image 20
Ahmad Hussain Avatar answered Sep 18 '22 12:09

Ahmad Hussain