自动链接html字符串中的URL和图像
嗨,我有一个像这样的字符串:
"http://vimeo/2342343
http://nerto.it/logo.png
try to write
http://vimeo/2234923
"
我必须在这样的字符串中转换它:
"try to write
"
那我怎么能得到每一个元素并改变它?
谢谢
html = "http://vimeo/2342343
http://nerto.it/logo.png
try to write
http://vimeo/2234923
" linked = html.gsub( %r{http://[^\s<]+} ) do |url| if url[/(?:png|jpe?g|gif|svg)$/] "" else "#{url}" end end puts linked #=> #=> #=> try to write
#=>
您可以使用自动链接function将链接转换为实际的锚标记。
auto_link(text_to_convert)
*注意:不推荐使用或移动方法此方法已弃用或在最新的稳定版本上移动。 最后一个现有版本(v3.0.9)显示在链接中。
如果您有更具体的用例,您可能希望将gsub与正则表达式一起使用。 例如:
text.gsub(/ \(。*?)\ <\ / p \> /,“
p>“)
auto_link函数已在此处移至单独的gem
使用Nokogiri而不是编写复杂的正则表达式。 下面的解决方案将完美地转换链接和图像。
需要'rubygems' 要求'nokogiri' #replace与你的字符串 str =“....” doc = Nokogiri :: HTML.parse(str) video_nodes = doc.css('。video') video_nodes.each do | v | content = v.content link_node = Nokogiri :: XML :: Node.new('a',doc) link_node ['href'] =内容 link_node.content = content v.add_child(link_node) 结束 img_nodes = doc.css('。image') img_nodes.each做| img | content = img.content image_node = Nokogiri :: XML :: Node.new('img',doc) image_node ['src'] =内容 img.add_child(image_node) 结束 把doc.to_html放进去
我想建议你将所有url从文本转换为链接的新的伟大gem是gem link_url 。 它也适用于没有gem的www。
gem install link_url
Example 1: LinkUrl.convert('hello I am on www.stackoverflow.com') Result => hello I am on www.stackoverflow.com Example 2: LinkUrl.convert('hello I am on www.stackoverflow.com and my blog is http://www.clecotech.in') Result => hello I am on www.stackoverflow.com and my blog is http://www.clecotech.in
尝试这个简单的最佳gem将所有url从文本或字符串转换为链接。 它还将图像URL转换为图像标记。
gem install url_link
string = "Welcome to my website http://www.mywebsite.com" url_link(format(string)) result => welcome to my website http://www.mywebsite.com image_string = "http://sofzh.miximages.com/ruby-on-rails/screenshot.png" url_link(format(image_string)) result => string = "Welcome to my website http://www.mywebsite.com see the picture http://media.smashingmagazine.com/images/introduction-to-rails/rails.jpg" url_link(format(string)) result => welcome to my website http://www.mywebsite.comsee the picture
或者尝试另一个
帮手
def proper_url_link(url_link) unless url_link.blank? url_link.gsub( %r{(http|https)://[^\s<]+} ) do |url| if url[/(?:png|jpe?g|gif|svg)$/] "" else "#{url} " end end end end def proper_html(html_format) unless html_format.blank? html_format.html_safe end end View html = "http://www.vimeo.com/2342343
<=proper_html(proper_url_link(html))%>