2
a = 'some string'
b = URI.encode(a) # returns 'some%20string'
c = URI.encode(b) # returns 'some%2520string'

ruby 中有没有一种方法可以解码'c',让我在不解码两次的情况下得到'a'字符串。我的观点是我有一些字符串被编码两次,而另一些字符串被编码一次。我想要一种自动解码为正常字符串的方法,自动识别解码的时间数。

4

3 回答 3

12

我想实现这一点的唯一方法是继续解码,直到它停止进行更改。我最喜欢这种东西的是do while循环:

decoded = encoded
begin
  decoded = URI.decode(decoded) 
end while(decoded != URI.decode(decoded)  )

恕我直言,您正在寻找的东西不存在。

******** 编辑 *************

stackoverflow 上的另一个重复问题的答案也暗示了相同的 如何找出字符串是否已经被 URL 编码?

于 2013-08-21T10:57:35.987 回答
2

我在文档中找不到自动检测,但可以通过一个额外的#decode调用通过以下方式实现这一点:

def decode_uri(uri)
  current_uri, uri = uri, URI.decode(uri) until uri == current_uri
  uri
end

它将一直调用#decodeuri直到它停止对其进行任何更改。

于 2013-08-21T10:51:01.363 回答
-1

这对我有用:

def decode_uri(encoded)
  decoded = encoded
  begin
    decoded = URI.decode(decoded)
  end while(decoded != URI.decode(decoded))
  return decoded
end
于 2017-01-24T07:28:19.737 回答