html - 如何删除特定标签但保留允许的标签

标签 html ruby parsing nokogiri

在一些 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/

相关文章:

mysql - mysql2 gem 安装失败

ios - 如何从 Objective C 中的 JSONP 中删除回调参数以使其可用?

html - 如何在 <td> 中居中对齐按钮?

javascript - 如何使用 HTTP POST 请求将参数发送到 Iframe

jquery - css 中的边框半径和背景颜色冲突

Python:将逻辑字符串解析为列表列表

excel - 根据左列单元格组合相邻行单元格

php - 更改 Woocommerce 产品页面上价格范围的字体大小

ruby-on-rails - 无法安装 rails 3.2.9 : Failed to build gem native extension

ruby-on-rails - Ruby on Rails 路径助手