2012-04-13 9 views
10

क्या HTML को नोकोगिरी के साथ सादे पाठ में परिवर्तित करना संभव है? मैं <br /> टैग भी शामिल करना चाहता हूं।एचटीएमएल को सादे पाठ में परिवर्तित करें (<br> एस के साथ)

उदाहरण के लिए

, इस HTML दिया:

ala ma kota 
i kot to idiota 

जब मैं सिर्फ फोन Nokogiri::HTML(my_html).text यह <br /> टैग शामिल नहीं:

ala ma kota i kot to idiota 
+1

एक gdzie 'dupa'? –

उत्तर

17

जटिल regexp लिखने के बजाय मैंने नोकोगिरी का उपयोग किया।

कार्य समाधान (K.I.S.S!):

def strip_html(str) 
    document = Nokogiri::HTML.parse(str) 
    document.css("br").each { |node| node.replace("\n") } 
    document.text 
end 
+1

उत्कृष्ट, धन्यवाद। – AGS

8

कुछ भी नहीं है इस तरह

<p>ala ma kota</p> <br /> <span>i kot to idiota </span> 

मैं इस उत्पादन चाहते हैं डिफ़ॉल्ट रूप से मौजूद है, लेकिन आप आसानी से कुछ मिलकर आसानी से हैक कर सकते हैं वांछित उत्पादन के लिए:

require 'nokogiri' 
def render_to_ascii(node) 
    blocks = %w[p div address]      # els to put newlines after 
    swaps = { "br"=>"\n", "hr"=>"\n#{'-'*70}\n" } # content to swap out 
    dup = node.dup         # don't munge the original 

    # Get rid of superfluous whitespace in the source 
    dup.xpath('.//text()').each{ |t| t.content=t.text.gsub(/\s+/,' ') } 

    # Swap out the swaps 
    dup.css(swaps.keys.join(',')).each{ |n| n.replace(swaps[n.name]) } 

    # Slap a couple newlines after each block level element 
    dup.css(blocks.join(',')).each{ |n| n.after("\n\n") } 

    # Return the modified text content 
    dup.text 
end 

frag = Nokogiri::HTML.fragment "<p>It is the end of the world 
    as   we 
    know it<br>and <i>I</i> <strong>feel</strong> 
    <a href='blah'>fine</a>.</p><div>Capische<hr>Buddy?</div>" 

puts render_to_ascii(frag) 
#=> It is the end of the world as we know it 
#=> and I feel fine. 
#=> 
#=> Capische 
#=> ---------------------------------------------------------------------- 
#=> Buddy? 
0

प्रयास करें

Nokogiri::HTML(my_html.gsub('<br />',"\n")).text 
0

Nokogiri लिंक नहीं हटेगा, तो मैं यह पहली बार उपयोग पाठ संस्करण में लिंक को बचाने के लिये:

html_version.gsub!(/<a href.*(http:[^"']+).*>(.*)<\/a>/i) { "#{$2}\n#{$1}" } 

कि इस बदल जाएगी :

<a href = "http://google.com">link to google</a> 

यह:

link to google 
http://google.com 
0

आप Haml का उपयोग करते हैं आप 'कच्चे' विकल्प, उदा साथ एचटीएमएल रखकर परिवर्तित एचटीएमएल हल कर सकते हैं

 = raw @product.short_description 
संबंधित मुद्दे