Ruby-on-rails 解析字符串以添加到 URL 编码的 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17375947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing string to add to URL-encoded URL
提问by Mohamed El Mahallawy
Given the string:
鉴于字符串:
"Hello there world"
how can I create a URL-encoded string like this:
如何创建这样的 URL 编码字符串:
"Hello%20there%20world"
I would also like to know what to do if the string has other symbols too, like:
我还想知道如果字符串也有其他符号该怎么办,例如:
"hello there: world, how are you"
What would is the easiest way to do so? I was going to parse and then build some code for that.
这样做的最简单方法是什么?我打算解析然后为此构建一些代码。
回答by Arie Xiao
In 2019, URI.encode is obsolete and should not be used
2019 年,URI.encode 已过时,不应使用
If you want safely put encrypted string into url without problems with special characters then you could use CGI.escapeor ERB::Util.url_encodefor this purpose.
如果您想安全地将加密字符串放入 url 中而不会出现特殊字符问题,那么您可以使用CGI.escape或ERB::Util.url_encode用于此目的。
require 'cgi'
CGI.escape("Hello world")
#=> "Hello+world"
Rails will decode automatically when receiving
Rails 接收时会自动解码
回答by Benjamin
While the current answer says to utilize URI.encodethat has been deprecated and obsolete since Ruby 1.9.2. It is better to utilize CGI.escapeor ERB::Util.url_encode.
虽然当前的答案说使用URI.encode自 Ruby 1.9.2 以来已被弃用和过时。最好使用CGI.escape或ERB::Util.url_encode。
回答by the Tin Man
Ruby's URIis useful for this. You can build the entire URL programmatically and add the query parameters using that class, and it'll handle the encoding for you:
Ruby 的URI对此很有用。您可以以编程方式构建整个 URL 并使用该类添加查询参数,它会为您处理编码:
require 'uri'
uri = URI.parse('http://foo.com')
uri.query = URI.encode_www_form(
's' => "Hello there world"
)
uri.to_s # => "http://foo.com?s=Hello+there+world"
The examples are useful:
这些例子很有用:
URI.encode_www_form([["q", "ruby"], ["lang", "en"]])
#=> "q=ruby&lang=en"
URI.encode_www_form("q" => "ruby", "lang" => "en")
#=> "q=ruby&lang=en"
URI.encode_www_form("q" => ["ruby", "perl"], "lang" => "en")
#=> "q=ruby&q=perl&lang=en"
URI.encode_www_form([["q", "ruby"], ["q", "perl"], ["lang", "en"]])
#=> "q=ruby&q=perl&lang=en"
These links might also be useful:
这些链接也可能有用:
- When to encode space to plus (+) or %20?
- URL encoding the space character: + or %20?
- 17.13.4 Form content typesfrom the W3's "Forms in HTML documents" recommendations.
- 何时将空格编码为加号 (+) 或 %20?
- URL 编码空格字符:+ 或 %20?
- 17.13.4来自 W3 的“HTML 文档中的表单”建议的表单内容类型。

