Ruby: Escaping special characters in a string

后端 未结 5 1092
终归单人心
终归单人心 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: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
    

提交回复
热议问题