我正在尝试编写一个与 PHP 中的 mysqli_real_escape_string
相同的方法。它接受一个字符串并转义任何“危险”字符。我一直在寻找一种可以为我做到这一点的方法,但我找不到。所以我想自己写一个。
这是我目前所拥有的(我在 Rubular.com 测试了模式并且它有效):
# 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
我使用 start_string
作为我想要更改的字符串,使用 correct_string
作为我希望 start_string
变成的字符串:
start_string = %("My" 'name' *is* -john- .doe. /ok?/ C:\\Drive)
correct_string = %(\"My\" \'name\' \*is\* \-john\- \.doe\. \/ok?\/ C:\\\\Drive)
有人可以尝试帮助我确定为什么我没有得到我想要的输出 (correct_string
) 或者告诉我在哪里可以找到执行此操作的方法,或者最好告诉我两者?非常感谢!
最佳答案
您的示例中的模式定义不正确。这是我所能达到的最接近您期望的输出。
输出
"\\\"My\\\" \\'name\\' \\*is\\* \\-john\\- \\.doe\\. \\/ok?\\/ C:\\\\Drive"
您需要进行一些调整才能 100% 完成,但至少您现在可以看到您的模式在起作用。
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
关于Ruby:转义字符串中的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4140582/