2012-04-13 28 views

答えて

17

複雑な正規表現を書くのではなく、ノコギリを使用しました。

作業溶液(K.I.S.S!):あなたはHAMLを使用している場合は、 '生の' オプション、f.e.でHTMLを置くことによってHTML変換を解決することができます

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

素晴らしい、ありがとう。 – AGS

8

ナッシング:

ala ma kota 
i kot to idiota 

私はちょうどそれが<br />タグを除外Nokogiri::HTML(my_html).textを呼び出す:

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

が、私はこの出力をしたい:このHTML与え例えば

、デフォルトでは存在しますが、近くにあるものを簡単にハックすることができます所望の出力に:

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

これをオンにします:

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

鋸山は、リンクを取り除くになるので、私はテキストバージョンでリンクを維持するために、この最初のを使用してみてください:

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

これは

link to google 
http://google.com 
0

 = raw @product.short_description 
関連する問題