Ruby:转义字符串中的特殊字符
我正在尝试编写一个与 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 )或告诉我在哪里可以找到执行此操作的方法,或者更好地告诉我两者?多谢!
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
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)
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您的示例中的模式定义不正确。这是我能得到的最接近您想要的输出的结果。
输出
您需要进行一些调整才能达到 100%,但至少您现在可以看到您的模式正在运行。
Your pattern isn't defined correctly in your example. This is as close as I can get to your desired output.
Output
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.
我已经像这样更改了上面的函数:
这对于正则表达式非常有用
I have changed above function like this:
This is working great for regex
这应该可以帮助您开始:
This should get you started:
查看 ActiveRecord 清理方法:http://api. rubyonrails.org/classes/ActiveRecord/Base.html#method-c-sanitize_sql_array
Take a look at the ActiveRecord sanitization methods: http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-sanitize_sql_array
这里查看Mysql类中的escape_string / quote方法
Take a look at escape_string / quote method in Mysql class here