将HTML转换为正确的纯文本?

Coj*_*nes 11 ruby-on-rails html-to-text ruby-on-rails-3

有什么办法可以将HTML转换为正确的纯文本吗?我尝试了从raw到sanitize的所有东西,甚至还有使用text_part方法的Mail gem,它本应该做到这一点,但对我来说不起作用.

到目前为止,我最好的射门是,strip_tags(strip_links(resource.body))但等等没有正确转换.<p><ul>

这或多或少是我在HTML中的含义:

Hello

This is some text. Blah blah blah.

Address:
John Doe
10 ABC Street
Whatever City

New Features
- Feature A
- Feature B
- Feature C
Check this out: http://www.google.com

Best,
Admin
Run Code Online (Sandbox Code Playgroud)

转换成类似的东西

Hello
This is some text. Blah blah blah.
Address: John Doe 10 ABC Street Whatever City

New Features Feature A Feature B Feature C
Check this out: http://www.google.com

Best, Admin
Run Code Online (Sandbox Code Playgroud)

任何的想法?

小智 15

Rails 4.2.1有#strip_tags一个内置的方法,特别是用于剥离HTML标记.

一些例子:

strip_tags("Strip <i>these</i> tags!")
Run Code Online (Sandbox Code Playgroud)

=>剥离这些标签!

strip_tags("<b>Bold</b> no more!  <a href='more.html'>See more here</a>...")
Run Code Online (Sandbox Code Playgroud)

=>大胆不再!在这里看到更多......

strip_tags("<div id='top-bar'>Welcome to my website!</div>")
Run Code Online (Sandbox Code Playgroud)

=>欢迎来到我的网站!

API文档中查看它.

  • 这并不能解决大多数所见即所得的编辑似乎都在使用的问题. (3认同)

Coj*_*nes 7

在这里找到解决方案:https://github.com/alexdunae/premailer/blob/master/lib/premailer/html_to_plain_text.rb

奇迹般有效!

  • 请注意,它使用正则表达式 H̸̡̪̯ͨ͊̽̅̾̎ş̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M͊̒ͪͩͬ̚解析html。 ̲̖̚͜ş̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ (3认同)