`

ruby 去掉字符串中的html代码讨论

阅读更多

从网上查到rails中去掉字符串中的html标签 的方法如下:

#去掉html标签,取出文本部分 ,并按指定的长度切断返回字符串。
 def strip_html(text,len=0,endss="...")

   if text.length>0
    attribute_key = /[w:_-]+/
    attribute_value = /(?:[A-Za-z0-9]+|(?:'[^']*?'|"[^"]*?"))/
    attribute = /(?:#{attribute_key}(?:s*=s*#{attribute_value})?)/
    attributes = /(?:#{attribute}(?:s+#{attribute})*)/
    tag_key = attribute_key
    tag = %r{<[!/?[]?(?:#{tag_key}|--)(?:s+#{attributes})?s*(?:[!/?]]+|--)?>}
    ss=text.gsub(tag, '').gsub(/s+/, ' ').strip
   
    if len>0 && ss.length>0
    ss=sub_utf8(ss,len,endss)
    end
   end
   return ss
 end

但是在我的工程中不是太起作用,还不如一个小小的正则表达式给力,如下:

@str.gsub(/<\/?.*?>/,"")

我觉得@str.gsub(/<\/?.*?>/,"")也可以把html标签去除的很干净,还没遇到什么问题,上面那个函数确实也很不错,但是。。。。给出参考,希望有兴趣的童鞋可以试试,最好能向我反馈一下效果哈,谢谢大家了。

 

1
4
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics