Tuesday, July 03, 2007

Ruby url_encode

require 'cgi'
require 'erb'
require 'uri'

str = "<a href='http://www.google.com'>'Stop!' said Fred</a>"
url_encoded_string = CGI::escape(str)
puts url_encoded_string

url_encoded_str2 = URI::escape(str)
puts url_encoded_str2

url_encoded_3 = ERB::Util.url_encode(str)
puts url_encoded_3

# >> %3Ca+href%3D%27http%3A%2F%2Fwww.google.com%27%3E%27Stop%21%27+said+Fred%3C%2Fa%3E
# >> %3Ca%20href='http://www.google.com'%3E'Stop!'%20said%20Fred%3C/a%3E
# >> %3Ca%20href%3D%27http%3A%2F%2Fwww.google.com%27%3E%27Stop%21%27%20said%20Fred%3C%2Fa%3E

3个方法输出的结果都不一样,最后用ERB::Util.url_encode(str)方法获取得同php5中的urlencode()方法得到的结果。

No comments :