foo*_*bar 10 ruby url escaping
这个网址:
http://gawker.com/5953728/if-alison-brie-and-gillian-jacobs-pin-up-special-doesnt-get-community-back-on-the-air-nothing-will-[nsfw]
Run Code Online (Sandbox Code Playgroud)
应该:
http://gawker.com/5953728/if-alison-brie-and-gillian-jacobs-pin-up-special-doesnt-get-community-back-on-the-air-nothing-will-%5Bnsfw%5D
Run Code Online (Sandbox Code Playgroud)
但是当我将第一个传递进去时URI.encode,它并没有逃过方括号.我也尝试过CGI.escape,但也逃脱了所有'/'.
我应该使用什么来正确转义URL?为什么不URI.encode逃避方括号?
小智 14
您可以逃脱[与%5B和]带%5D.
您的网址将是:
URL.gsub("[","%5B").gsub("]","%5D")
Run Code Online (Sandbox Code Playgroud)
我不喜欢这个解决方案,但它正在发挥作用.
cHa*_*Hao 10
encode 不会转义括号,因为它们并不特殊 - 它们在URI的路径部分没有特殊含义,因此它们实际上不需要转义.
如果你想要转义除"不安全"之外的字符,请将第二个arg传递给encode方法.那个arg应该是一个正则表达式匹配,或者是一个包含你想要编码的每个字符的字符串(包括该函数否则已经匹配的字符!).
小智 5
如果使用第三方 gem 是一种选择,请尝试addressable。
require "addressable/uri"
url = Addressable::URI.parse("http://[::1]/path[]").normalize!.to_s
#=> "http://[::1]/path%5B%5D"
Run Code Online (Sandbox Code Playgroud)
注意归一化!方法不仅会转义无效字符,还会对主机名部分执行大小写折叠,对不必要的转义字符进行转义等:
uri = Addressable::URI.parse("http://Example.ORG/path[]?query[]=%2F").normalize!
url = uri.to_s #=> "http://example.org/path%5B%5D?query%5B%5D=/"
Run Code Online (Sandbox Code Playgroud)
因此,如果您只想规范化路径部分,请执行以下操作:
uri = Addressable::URI.parse("http://Example.ORG/path[]?query[]=%2F")
uri.path = uri.normalized_path
url = uri.to_s #=> "http://Example.ORG/path%5B%5D?query[]=%2F"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10802 次 |
| 最近记录: |