在一些 HTML 中,我想删除一些特定的标签,但保留标签的内容/HTML。例如,在下面的行中,我
想要删除 <strong>
和 <div>
列入黑名单的标签,但保留标签的内容,并保留 <p>
, <img>
和我的白名单标签中的其他标签:
原文:
<div>
some text
<strong>text</strong>
<p>other text</p>
<img src="http://example.com" />
</div>
结果:
some text
text
<p>other text</p>
<img src="http://example.com" />
我想要剥离特定的标签,有些标签不能被剥离。它必须像 strip_tags
一样工作在 PHP 中。所以inner_html
帮不了我。
最佳答案
我会做类似的事情:
require 'nokogiri'
doc = Nokogiri::HTML(<<EOT)
<div>
some text
<strong>text</strong>
<p>other text</p>
<img src="http://example.com" />
</div>
EOT
BLACKLIST = %w[strong div]
doc.search(BLACKLIST.join(',')).each do |node|
node.replace(node.children)
end
puts doc.to_html
# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
# >> <html><body>
# >> some text
# >> text
# >> <p>other text</p>
# >> <img src="http://example.com">
# >>
# >> </body></html>
基本上它会在BLACKLIST
中查找节点,并在文档中的任何位置找到它们,将它们替换为该节点的children
,有效地提升子节点给他们的 parent 。
关于html - 如何删除特定标签但保留允许的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32608549/