ab217
ab217

Reputation: 17170

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!

Upvotes: 12

Views: 41212

Answers (5)

Ahmad Hussain
Ahmad Hussain

Reputation: 2491

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

Upvotes: 4

rwilliams
rwilliams

Reputation: 21497

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

Upvotes: 15

the Tin Man
the Tin Man

Reputation: 160621

This should get you started:

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

Upvotes: 2

letronje
letronje

Reputation: 9148

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

Upvotes: 0

ehsanul
ehsanul

Reputation: 7766

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

Upvotes: 1

Related Questions