2013-10-28 192 views
2

使用Rails 3.2。我想删除<b>所有文字和标签,但我想尽办法剥去标签只:删除特定标签内的内容

string = " 
    <p> 
    <b>Section 1</b> 
    Everything is good.<br> 
    <b>Section 2</b> 
    All is well. 
    </p>" 
string.strip_tags 
# => "Section 1 Everthing is good. Section 2 All is well." 

我要实现这一点:

"Everthing is good. All is well." 

我要补充正则表达式匹配太?

回答

2

“正确”的方法是使用HTML解析器像Nokogiri
但是,对于这个简单的任务,你可以使用正则表达式。这很简单:
搜索:(?m)<b\s*>.*?<\/b\s*>并将其替换为空字符串。之后,使用strip_tags

正则表达式的解释:

(?m) # set the m modifier to match newlines with dots . 
<b  # match <b 
\s*  # match a whitespace zero or more times 
>  # match > 
.*?  # match anything ungreedy until </b found 
<\/b # match </b 
\s*  # match a whitespace zero or more times 
>  # match > 

Online demo

3

将HTML/XML解析器用于此任务会好得多。 Ruby没有原生一个,但Nokogiri好,包装的libxml/XSLT

doc = Nokogiri::XML string 
doc.xpath("//b").remove 
result = doc.text # or .inner_html to include `<p>` 
0

,如果你想删除的标签,你可以试试这个:

ActionController::Base.helpers.sanitize("test<br>test<br>test<br> test") 
如果你想删除你需要使用这个所有标签

ActionView::Base.full_sanitizer.sanitize("test<br>test<br>test<br> test") 

这两个不同slightly.the第一个是好的脚本标记,以防止XSS攻击,但是它不删除tages。第二个删除文本中的任何html标签。

相关问题