module CGI::Util
def escape(string)
url_encoded_string = CGI.escape("'Stop!' said Fred")
Space characters (+" "+) are encoded with plus signs (+"+"+)
URL-encode a string into application/x-www-form-urlencoded.
def escape(string) encoding = string.encoding buffer = string.b buffer.gsub!(/([^ a-zA-Z0-9_.\-~]+)/) do |m| '%' + m.unpack('H2' * m.bytesize).join('%').upcase end buffer.tr!(' ', '+') buffer.force_encoding(encoding) end
def escapeElement(string, *elements)
<A HREF="url"></A>"
print CGI.escapeElement('
', ["A", "IMG"])
# "
<A HREF="url"></A>"
print CGI.escapeElement('
', "A", "IMG")
instance, the double-quotes surrounding attribute values).
The attribute list of the open tag will also be escaped (for
This matches both the start and the end tag of that element.
is specified by the name of the element, without angle brackets.
Takes an element or elements or array of elements. Each element
Escape only the tags of certain HTML elements in +string+.
def escapeElement(string, *elements) elements = elements[0] if elements[0].kind_of?(Array) unless elements.empty? string.gsub(/<\/?(?:#{elements.join("|")})\b[^<>]*+>?/im) do CGI.escapeHTML($&) end else string end end
def escapeHTML(string)
CGI.escapeHTML('Usage: foo "bar"
Escape special characters in HTML, namely '&\"<>
def escapeHTML(string) enc = string.encoding unless enc.ascii_compatible? if enc.dummy? origenc = enc enc = Encoding::Converter.asciicompat_encoding(enc) string = enc ? string.encode(enc) : string.b end table = Hash[TABLE_FOR_ESCAPE_HTML__.map {|pair|pair.map {|s|s.encode(enc)}}] string = string.gsub(/#{"['&\"<>]".encode(enc)}/, table) string.encode!(origenc) if origenc string else string = string.b string.gsub!(/['&\"<>]/, TABLE_FOR_ESCAPE_HTML__) string.force_encoding(enc) end end
def escapeURIComponent(string)
url_encoded_string = CGI.escapeURIComponent("'Stop!' said Fred")
Space characters (+" "+) are encoded with (+"%20"+)
URL-encode a string following RFC 3986
def escapeURIComponent(string) encoding = string.encoding buffer = string.b buffer.gsub!(/([^a-zA-Z0-9_.\-~]+)/) do |m| '%' + m.unpack('H2' * m.bytesize).join('%').upcase end buffer.force_encoding(encoding) end
def pretty(string, shift = " ")
#