Ruby:将 <br> 转换为换行 URI 编码

问题描述 投票:0回答:2

我想在 Whatsapp 上分享一些文本,所以我将 html 转换为文本,否则它会显示所有标签。

目前我正在使用 strip_tags 来删除标签,但这也删除了文本中的中断。如何将 html 转换为文本并将换行符转换为换行符并对文本进行 url 编码。

目前我正在使用以下

@whatsapp_text = u strip_tags(@post.summary)
ruby-on-rails ruby line-breaks whatsapp uriencoding
2个回答
2
投票

我建议你使用Nokogiri来解决这个问题。 Nokogiri 可以解析 HTML 并将网站源代码转换为人类可读的文本,尽管它不会将 html 中断转换为换行符,但它可以解决您的许多问题。为此,请将以下行添加到您的

Gemfile

gem 'nokogiri'

运行

bundle install
。然后你可以这样解决你的问题:

Nokogiri::HTML.parse(@post.summary.gsub("<br>", "\r\n").gsub("<br/>", "\r\n")).inner_text

这应该适合你。


0
投票

ActionView::Helpers::SanitizeHelper#sanitize
scrubber: :newline_block_elements
选项可以保留空白字符(参考:https://github.com/rails/rails-html-sanitizer/issues/154#issuecomment-1551819784)。

在这里提及

ActionView
,因为问题被标记为
ruby-on-rails
。可以直接将
Loofah
gem
Loofah::Scrubbers::NewlineBlockElements
洗涤器
一起使用。

# $ rails console
helper.sanitize("<div><p>text<br><br></p><span>another text</span><p>wow nested paragraph!!</p></p>", scrubber: :newline_block_elements)
# => "\n\ntext\nanother text\nwow nested paragraph!!\n\n"
© www.soinside.com 2019 - 2024. All rights reserved.