Remove a tag but keep the text

流过昼夜 提交于 2019-12-01 12:44:56

Here is what I would do :

require 'nokogiri'

doc = Nokogiri::HTML.parse <<-eot
<a href="/www.somethinggggg.com">Something 123</a>
eot

node = doc.at("a")
node.replace(node.text)

puts doc.to_html

output

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org
   /TR/REC-html40/loose.dtd">
<html>
   <body>Something 123</body>
</html>

Update

What if I have an array that holds content with links?

Hint

require 'nokogiri'

doc = Nokogiri::HTML.parse <<-eot
<a href="/www.foo.com">foo</a>
<a href="/www.bar.com">bar</a>
<a href="/www.baz.com">baz</a>
eot

arr = %w(foo bar baz)
nodes = doc.search("a")
nodes.each {|node| node.replace(node.content) if arr.include?(node.content) }

puts doc.to_html

output

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org
   /TR/REC-html40/loose.dtd">
<html>
   <body>foo
      bar
      baz
   </body>
</html>

Generic way to unwrap tag is — node.replace(node.children), eg.:

doc = Nokogiri::HTML.fragment('<div>A<i>B</i>C</div>')
doc.css('div').each { |node| node.replace(node.children) }
doc.inner_html #=> "A<i>B</i>C"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!