我正在尝试编写一个与
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') #
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)或者告诉我在哪里可以找到这样做的方法,或者更好地告诉我两者?非常感谢!