HTML清洗和关闭不完整的标签

6
ApplicationHelper中的sanitize()方法没有关闭标签。
s = "<a href='http://example.com'>incomplete"
sanitize(s, :tags => ['a', 'p'])

上述代码片段会保留原始字符串。如何强制它添加一个闭合标签</a>或至少将<a>标签删除?

2个回答

5
你可以使用一个合适的HTML解析器来实现此功能。我建议使用Nokogiri工具来处理:
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>"

这将始终返回有效的XML。当然,您可以将其打包到自己的辅助方法中,以便更轻松地使用。

谢谢,但是我看到TypeError: can't convert Symbol into Integer的响应,它可以处理纯文本。这是Nokogiri 1.5.2。 - mahemoff
@mahemoff: 这里Nokogiri::HTML::fragment("<a href='http://example.com'>incomplete").to_xml很好用。你尝试的实际标签混乱是什么? - Niklas B.
实际上,它看起来是传递给sanitize的第二个参数。就像原始问题中一样,允许的标签需要在哈希中,以:tags =>为键。Nokogiri :: HTML :: fragment(sanitize('test <a href =“http://example.com”> incomplete',:tags => ['a','p']))。to_xml可以工作。 - mahemoff
顺便提一下,当我处理国际化时,我注意到 to_xml 可能最好改为 to_html。后者会转义Unicode实体,例如 &#123。 - mahemoff

2

更新后的答案是

 s = "<a href='http://example.com'>incomplete"
 html = sanitize(s, tags: %w[a p])
 Nokogiri::HTML::DocumentFragment.parse(html).to_html

最后一行单独使用对我非常有效,而且还关闭了未关闭的标签。 - Max Williams

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接