2011-02-09 28 views

回答

18

Rails有一個auto_link文本幫助程序。

auto_link("Go to http://www.rubyonrails.org and say hello to [email protected]") 
# => "Go to <a href=\"http://www.rubyonrails.org\">http://www.rubyonrails.org</a> and 
#  say hello to <a href=\"mailto:[email protected]\">[email protected]</a>" 

auto_link("Visit http://www.loudthinking.com/ or e-mail [email protected]", :link => :urls) 
# => "Visit <a href=\"http://www.loudthinking.com/\">http://www.loudthinking.com/</a> 
#  or e-mail [email protected]" 
+0

我從來沒有聽說過。大! – fl00r 2011-02-09 10:33:42

-3

首先,你應該定義一個正則表達式匹配的HTTP字符串,例如

 
IPv4_PART = /\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]/ # 0-255 
REGEXP = %r{ 
    https?://             # http:// or https:// 
    ([^\s:@]+:[^\s:@]*@)?          # optional username:[email protected] 
    ((([^\W_]+\.)*xn--)?[^\W_]+([-.][^\W_]+)*\.[a-z]{2,6}\.? | # domain (including Punycode/IDN)... 
     #{IPv4_PART}(\.#{IPv4_PART}){3})      # or IPv4 
    (:\d{1,5})?             # optional port 
    ([/?]\S*)?             
}iux 

然後,假設評論身體海峽,你這樣做:

 
str.gsub(REGEXP) do |m| 
    link_to m, m 
end 
+1

滾動自己的網址匹配是一個非常可怕的想法 - 你** **會犯錯誤。使用圖書館。 :) – 2011-05-19 11:29:16

0

您可以同時使用「auto_html 「寶石,見https://github.com/dejan/auto_html

聲明:還沒有使用它,但它看起來可以做你想做的。

+0

它不僅僅是要求提出的問題,這很有趣,但需要一個新的寶石。 auto_link更簡單。 – 2011-03-02 04:38:18

0

我還建議您考慮一下像Markdown這樣的東西,以供您評論。然後你可以讓Markdown引擎爲你擔心這樣的東西。

相關問題