我正在尝试编写一个与
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。