【问题标题】:Ruby equivalent to PHPs urlencodeRuby 相当于 PHP 的 urlencode
【发布时间】:2019-06-28 05:57:56
【问题描述】:

我需要在 Ruby 中转换一个包含字符“ö”的 URL。

在 PHP 中,urlencode 返回 ö 的 %F6,这似乎是 ISO 8859 中“ö”的十六进制值。

我尝试了几种不同的方法,但都没有返回正确的字符:

  • CGI.escape 'ö' -> %C3%B6
  • URI.encode 'o' -> %C3%B6
  • ERB::Util.url_encode 'ö' -> %C3%B6
  • 'ö'.force_encoding('iso-8859-1') -> \xC3\xB

我应该使用什么方法来获得所需的输出?

-e-

附加要求:

我只需要在url的路径中转换这些字符。冒号、斜杠等应保持不变:

http://example.com/this/is/an/ö

将会

http://example.com/this/is/an/%F6

【问题讨论】:

  • 你试过这个'ö'.encode("ISO-8859-1") 吗?
  • “在 PHP 中,urlencode 返回 ö 的 %F6” – 视情况而定。如果将 UTF-8 字符串传递给 PHP 的 urlencode,它也会返回 %C3%B6

标签: ruby-on-rails ruby encoding iso-8859-1


【解决方案1】:

Ruby 默认使用 UTF-8 字符串:

str = 'ö'

str.encoding
#=> #<Encoding:UTF-8>

如果您想在 Ruby 中使用 ISO 8859 编码的字符串,则必须对其进行转换:

str.encode('ISO-8859-1')
#=> "\xF6"

要对字符串进行 URL 编码,有 CGI.escape:

require 'cgi'

CGI.escape(str.encode('ISO-8859-1'))
#=> "%F6"

要对 URL 进行编码,请使用 URI.escape:

require 'uri'

url = 'http://example.com/this/is/an/ö'
URI.escape(url.encode('ISO-8859-1'))
#=> "http://example.com/this/is/an/%F6"

【讨论】:

  • 现在的问题是 url 中的每个字符都被转换了。例如,前斜杠是 %2F。有没有比将 url 拆分成各个部分并仅转换实际路径更好的方法?
  • @SanoJ 你的问题是关于ö,你没有提到任何斜线。也许您可以编辑您的问题并解释您要做什么。举个例子可能会有所帮助。
【解决方案2】:

我找到了解决办法

converter = Encoding::Converter.new("utf-8", "iso-8859-1")
CGI.escape(converter.convert('ö'))

=> "%F6"

【讨论】:

    猜你喜欢
    • 2012-06-07
    • 2012-10-05
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 2011-09-19
    • 1970-01-01
    • 2020-02-16
    相关资源
    最近更新 更多