Ruby中的url_encode
我阅读了url_encode
的文档 。
是否有一个表格使用url_encode
告诉我究竟哪个字符被编码url_encode
?
ERB的url_encode
可以调整:
def url_encode(s) s.to_s.dup.force_encoding("ASCII-8BIT").gsub(%r[^a-zA-Z0-9_\-.]/) { sprintf("%%%02X", $&.unpack("C")[0]) } end
至:
def url_encode(s, regex=%r[^a-zA-Z0-9_\-.]/) s.to_s.dup.force_encoding("ASCII-8BIT").gsub(regex) { sprintf("%%%02X", $&.unpack("C")[0]) } end url_encode('pop', /./) => "%70%6F%70"
此外,Ruby的CGI和URI模块能够编码URL,将受限制的字符转换为实体,因此不要忽视它们的产品。
例如,转义URL参数的字符:
CGI.escape('http://www.example.com') => "http%3A%2F%2Fwww.example.com" CGI.escape('foo
') => "%3Cbody%3E%3Cp%3Efoo%3C%2Fp%3E%3C%2Fbody%3E"
Ruby CGI的escape
也使用一个小的正则表达式来确定哪些字符应该在URL中转义。 这是文档中方法的定义:
def CGI::escape(string) string.gsub(%r([^ a-zA-Z0-9_.-]+)/) do '%' + $1.unpack('H2' * $1.bytesize).join('%').upcase end.tr(' ', '+') end
您还可以覆盖它并更改正则表达式,或者在重新定义方法时将其公开以供自己使用:
def CGI::escape(string, escape_regex=%r([^ a-zA-Z0-9_.-]+)/) string.gsub(escape_regex) do '%' + $1.unpack('H2' * $1.bytesize).join('%').upcase end.tr(' ', '+') end
URI.encode_www_form_component
也做类似的编码,字符的唯一区别是*
和 :
URI.encode_www_form_component('foo
') => "%3Cp%3Efoo%3C%2Fp%3E"
并且,与覆盖CGI::escape
类似,您可以覆盖URI.encode_www_form_component
的正则表达式:
def self.encode_www_form_component(str, regex=%r[^*\-.0-9A-Z_a-z]/) str = str.to_s if HTML5ASCIIINCOMPAT.include?(str.encoding) str = str.encode(Encoding::UTF_8) else str = str.dup end str.force_encoding(Encoding::ASCII_8BIT) str.gsub!(regex, TBLENCWWWCOMP_) str.force_encoding(Encoding::US_ASCII) end