问题描述
我正在PHP中编写一个与 mysqli_real_escape_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
我正在使用 start_string
作为我想要更改的字符串,而 correct_string
正如我想要的那样 start_string
变成:
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)
有人可以帮助我确定为什么我没有得到我想要的输出( correct_string
)或告诉我在哪里可以找到一个这样做的方法,甚至更好地告诉我两者?非常感谢!
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!
推荐答案
您的示例中没有正确定义您的模式。
Your pattern isn't defined correctly in your example. This is as close as I can get to your desired output.
输出
"\\\"My\\\" \\'name\\' \\*is\\* \\-john\\- \\.doe\\. \\/ok?\\/ C:\\\\Drive"
将要采取一些调整,以获得100%,但至少可以看到您现在的行为模式。
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
这篇关于Ruby:在字符串中转义特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!