将 HTML 转换为纯文本(包含 <br>s) [英] Convert HTML to plain text (with inclusion of <br>s)
本文介绍了将 HTML 转换为纯文本(包含 <br>s)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以将带有 Nokogiri 的 HTML 转换为纯文本?我还想包含 <br/>
标签.
Is it possible to convert HTML with Nokogiri to plain text? I also want to include <br />
tag.
例如,给定这个 HTML:
For example, given this HTML:
<p>ala ma kota</p> <br /> <span>i kot to idiota </span>
我想要这个输出:
ala ma kota
i kot to idiota
当我只调用 Nokogiri::HTML(my_html).text
时,它排除了 <br/>
标签:
When I just call Nokogiri::HTML(my_html).text
it excludes <br />
tag:
ala ma kota i kot to idiota
推荐答案
我没有编写复杂的正则表达式,而是使用了 Nokogiri.
Instead of writing complex regexp I used Nokogiri.
工作解决方案(K.I.S.S!):
Working solution (K.I.S.S!):
def strip_html(str)
document = Nokogiri::HTML.parse(str)
document.css("br").each { |node| node.replace("\n") }
document.text
end
这篇关于将 HTML 转换为纯文本(包含 <br>s)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文