2013-10-28 193 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標籤。

相關問題