Ruby-on-rails 如何从字符串中删除 HTML 标记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15251746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove HTML markup from string
提问by gabrielhilal
Let's say I have:
假设我有:
@string = "it is a <a href="#">string</a>"
I want to use it in different parts of my application in two ways:
我想以两种方式在应用程序的不同部分使用它:
- With a clickable link
- Without the clickable link (but not showing any HTML markup)
- 带有可点击的链接
- 没有可点击的链接(但不显示任何 HTML 标记)
The first one can be done using html_safe:
第一个可以使用html_safe:
@string.html_safe
It is a string
它是一个字符串
How can I achieve the second one?
我怎样才能达到第二个?
It is a string.
它是一个字符串。
回答by ant
You can try this:
你可以试试这个:
ActionView::Base.full_sanitizer.sanitize(@string)
See strip_tags(html).
请参阅strip_tags(html)。
回答by Manoj Thapliyal
You can try this:
你可以试试这个:
strip_tags(@string)
回答by Benny
For general-purpose use (e.g. web scraper):
对于通用用途(例如网页刮刀):
puts Rails::Html::FullSanitizer.new.sanitize("<div>Hello</div><br>")
# Hello
回答by My God
You can use nokogirito do the same.
您可以使用nokogiri它来做同样的事情。
This SO posttells the story.
这篇SO帖子讲述了这个故事。
Here in short:
简而言之:
This uses the XPath's starts-withfunction:
这使用了 XPath 的starts-with函数:
You have to first define it like this:
您必须首先像这样定义它:
require 'nokogiri'
item = Nokogiri::HTML('<a href="#">string</a>')
puts item.to_html
The above will give the html output. Then you can use XPath.
以上将给出 html 输出。然后你可以使用XPath。
item.search('//a[not(starts-with(@href, "http://"))]').each do |a|
a.replace(a.content)
end
puts item.to_html
回答by piratebroadcast
In Rails, see also the strip_tags method. http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html#method-i-strip_tags
在 Rails 中,另请参见 strip_tags 方法。http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html#method-i-strip_tags
回答by Veger
Rails provides a method called strip_links, which seems to do what you want (looking at its name).
Rails 提供了一个名为 的方法strip_links,它似乎可以做你想做的事(看它的名字)。
According to its APIDock pageit is a bit limited. To make it applicable to a/any string you could extend the string class:
根据其 APIDock 页面,它有点受限。为了使其适用于一个/任何字符串,您可以扩展字符串类:
class String
def strip_links
ActionController::Base.helpers.strip_links(self)
end
end
So you can use:
所以你可以使用:
@string.strip_links

