在一些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" />我想要带特定标签和一些标签不能被剥离。它必须像PHP中的strip_tags那样工作。所以inner_html帮不了我。
发布于 2015-09-18 14:51:56
使用Rails::Html::WhiteListSanitizer
white_list_sanitizer = Rails::Html::WhiteListSanitizer.new
original = <<EOD
<div>
some text
<strong>text</strong>
<p>other text</p>
<img src="http://example.com" />
</div>
EOD
puts white_list_sanitizer.sanitize(original, tags: %w(p img))输出:
some text
text
<p>other text</p>
<img src="http://example.com">发布于 2015-09-22 00:18:56
我会做这样的事:
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替换它们,从而有效地将子节点提升到其父节点。
发布于 2015-09-21 12:20:18
在只使用Nokogiri的情况下,可以在节点上循环删除所有不必要的标记:
def clean_node(node, whitelist)
node.children.each do |n|
clean_node(n, whitelist)
unless whitelist.include?(n.name)
n.before(n.children)
n.remove
end
end
node
end
def strip_tags(html, whitelist)
whitelist += %w(text)
node = Nokogiri::HTML(html).children.last
clean_node(node, whitelist).inner_html
endstrip_tags函数将删除所有不在白名单中的标记。以你为例,你会做:
original = <<HTML
<div>
some text
<strong>text</strong>
<p>other text</p>
<img src="http://example.com" />
</div>
HTML
puts strip_tags(original, %w(p img))产出如下:
some text
text
<p>other text</p>
<img src="http://example.com">https://stackoverflow.com/questions/32608549
复制相似问题