提取并添加指向字符串中URL的链接

时间:2011-05-13 14:27:19

标签: ruby string url replace

我有几个字符串,其中包含链接。例如:

var str = "I really love this site: http://www.stackoverflow.com"

我需要添加一个链接标记,因此str将是:

I really love this site: <a href="http://www.stackoverflow.com">http://www.stackoverflow.com</a>

3 个答案:

答案 0 :(得分:3)

一种可能性是使用URI class让它进行解析。有点像这样:

require 'uri'

str = "I really love this site: http://www.stackoverflow.com"
url = str.slice(URI.regexp(['http']))
puts str.gsub( url, '<a href="' + url + '">' + url + '</a>' )

答案 1 :(得分:1)

您可以使用URI.extract:

str = "I really love this site: http://www.stackoverflow.com and also this one: http://www.google.com"

URI.extract(str, ['http', 'https']).each do |uri|
  str = str.gsub( uri, "<a href=\"#{uri}\">#{uri}</a>" )
end

str

以上内容还匹配一个字符串中的多个网址。

答案 2 :(得分:0)

在这里,工作代码:)也会在显示的链接中去除http / s前缀

请注意,您应该在uri +“”上使用正则表达式,以便它正确捕获链接...然后您需要在开头添加一个空格以在末尾捕获没有尾随空格的链接...

thisString = yourString+" " # add space to catch link at end
URI.extract(thisString, ['http', 'https']).each do |uri|
  linkURL = uri
  if(uri[0..6] == "http://")
    linkURL = uri[7..-1]
  elsif(uri[0..7] == "https://")
    linkURL = uri[8..-1]
  end
  thisString = thisString.gsub( uri+" ", "<a href=\"#{uri.to_s}\">#{linkURL.to_s}</a> " )
end