Ruby: Escaping special characters in a string

后端 未结 5 1087
终归单人心
终归单人心 2021-01-04 22:40

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 fo

相关标签:
5条回答
  • 2021-01-04 22:58

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

    0 讨论(0)
  • 2021-01-04 22:59

    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
    
    0 讨论(0)
  • This should get you started:

    print %("'*-.).gsub(/["'*.-]/){ |s| '\\' + s }
    \"\'\*\-\.
    
    0 讨论(0)
  • 2021-01-04 23:00

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

    0 讨论(0)
  • 2021-01-04 23:17

    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

    0 讨论(0)
提交回复
热议问题