HTML sanitize and close partial tags
2 answers
You can use the correct HTML parser for this. I would recommend Nokogiri for work:
require 'nokogiri' # ... s = "<a href='http://example.com'>incomplete" Nokogiri::HTML::fragment(sanitize(s, :tags => ['a', 'p'])).to_xml # => "<a href=\"http://example.com\">incomplete</a>"
This always returns valid XML. Of course, you can pack them into your own helper method for ease of use.
+5