简体   繁体   English

如何在ruby中将单引号替换为反斜杠?

[英]How to replace single quote to backslash in ruby?

In order to prevent sql injection, I did this: 为了防止sql注入,我这样做:

string = "105;' DROP TABLE Suppliers"
new_string = string.gsub("'", %q(\'))
p new_string
=> "105; DROP TABLE Suppliers DROP TABLE Suppliers"

Here why output DROP TABLE Suppliers twice? 在这里,为什么两次输出DROP TABLE Suppliers

Ruby is interpreting the \\' as a backreference to the post-match string($'). Ruby将\\'解释为对匹配后字符串($')的反向引用。 So, you are replacing the quote with everything after the quote: 因此,您将用引号后的所有内容替换引号:

<space>DROP TABLE Suppliers
     V
"105;' DROP TABLE Suppliers"

Here it is with a backreference to the pre-match variable($`): 这是对预匹配变量($`)的后向引用:

string = "105;' DROP TABLE Suppliers"
new_string = string.gsub("'", %q(\`))
p new_string

--output:--
"105;105; DROP TABLE Suppliers"

I can't find any documentation for backreferences to ruby's global variables, so congratulations you are a ruby pioneer. 我找不到任何有关ruby全局变量的反向引用的文档,因此恭喜您是ruby的先驱。

The good news is it turns out you don't have to do that. 好消息是事实证明您不必这样做。 For more in depth info read the comments bellow. 有关更多详细信息,请阅读下面的评论。 To escape a single quote, you add another single quote. 要转义单引号,请添加另一个单引号。 So the winner is: 因此获胜者是:

string.gsub(/'/, "''") 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM