Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Close forgotten HTML tags easily in user HTML input (See related posts)

If you let users type raw HTML into your input boxes, they will inevitably forget to close some of their tags from time to time. Close any forgotten tags with this:

h1 = {}
h2 = {}
code.scan(/\<([^\>\s\/]+)[^\>\/]*?\>/).each { |t| h1[t[0]] ? h1[t[0]] += 1 : h1[t[0]] = 1 }
code.scan(/\<\/([^\>\s\/]+)[^\>]*?\>/).each { |t| h2[t[0]] ? h2[t[0]] += 1 : h2[t[0]] = 1 }
h1.each {|k,v| code += "</#{k}>" * (h1[k] - h2[k].to_i) if h2[k].to_i < v }

Comments on this post

quilsone posts on Nov 07, 2007 at 20:42
the only problem with this is that it doesn't close the tags in the correct order, which can cause problems. without going overboard, this works a bit better:

  def close_tags(text)
    open_tags = []
    text.scan(/\<([^\>\s\/]+)[^\>\/]*?\>/).each { |t| open_tags.unshift(t) }
    text.scan(/\<\/([^\>\s\/]+)[^\>]*?\>/).each { |t| open_tags.slice!(open_tags.index(t)) }
    open_tags.each {|t| text += "</#{t}>" }
    text
  end

You need to create an account or log in to post comments to this site.


Click here to browse all 5147 code snippets

Related Posts