我在我的網站上有用戶生成的評論。如果用戶在他們的評論中添加了URL,我希望它被格式化爲鏈接並實際鏈接到該URL。我怎麼做?在Rails 3視圖中,如何檢測顯示字符串中的URL並將其格式化爲該URL的鏈接?
9
A
回答
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]"
-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引擎爲你擔心這樣的東西。
8
在Rails 3.1 auto_link有奔去除,其現在是一個獨立的寶石:https://github.com/tenderlove/rails_autolink
相關問題
- 1. 檢測URL並在UITextField中格式化
- 2. Rails 3 UTF-8查詢字符串顯示在URL中?
- 3. java字符串中的replaceAll「/」如何格式化URL?
- 4. 在字符串中間鏈接URL
- 5. .NET:如何將字符串顯示爲格式化的HTML?
- 6. 將字符串格式化爲只顯示最後3個字符,並將其他字符顯示爲RDLC中的星號
- 7. 如何在XSLT中將字符串格式化爲Pascal格式?
- 8. 的Rails 3 - 如何瑟的URL,如該表格將被髮送
- 9. as3 - 在動態文本中檢測URL並將它們鏈接
- 10. 如何將字符串追加到url然後讓url顯示字符串?
- 11. 檢測BotFramework中的加入鏈接Url
- 12. 如何在url中顯示?字符?
- 13. 使用URL生成鏈接預覽並檢測視頻/圖像!
- 14. 如何檢測url/image/youtube鏈接並將其附在標籤上
- 15. 提取並添加鏈接到字符串中的URL
- 16. 將字符串轉換爲浮動並將其格式化(C#)
- 17. 使用xamarin從URl中檢索JSON消息並在表格視圖中顯示
- 18. 如何格式化JsonString並將格式化的字符串放入數組中?
- 19. 如何檢測字符串是否包含java中的URL?
- 20. 如何檢測整數上的填充並將其視爲字符串?
- 21. 顯示鏈接後的URL?
- 22. 如何將模板鏈接到PyroCMS中的視圖和URL?
- 23. 如何在Java MessageDialog中創建超鏈接url字符串?
- 24. 在Rails URL中鏈接標籤鏈接
- 25. 如何傳遞Vue中的字符串並將其視爲html
- 26. PHP - 將鏈接添加到字符串中的URL
- 27. 檢查一個字符串中的URL,並返回一個HTML鏈接到它
- 28. JSON字符串與圖像url或JSON格式的url編碼
- 29. 使用PHP,搜索URL的字符串並將該URL保存爲值
- 30. 如何在grails 3中將gson視圖呈現爲字符串?
我從來沒有聽說過。大! – fl00r 2011-02-09 10:33:42