2011-05-13 66 views
2

我有幾個字符串中有鏈接。例如:提取並添加鏈接到字符串中的URL

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> 
+2

您可以使用如下所述的actionpack:http://stackoverflow.com/questions/1442143/ruby-linkify-for-urls-in-strings/1442382#1442382 – Mischa 2011-05-13 14:34:26

+0

[將URL和@ *轉換爲鏈接](http://stackoverflow.com/questions/4571229/turn-urls-and-into-links) – Phrogz 2011-05-13 15:24:35

回答

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>') 
0

您可以使用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 

以上同時匹配一個字符串多個網址。