Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn URLs and @* into links

Tags:

regex

ruby

I'm getting my latest tweets with HTTParty and Hashie like so.

tweet = Hashie::Mash.new HTTParty.get(http://twitter.com/statuses/user_timeline/ethnt.json).first
puts tweet.text

I want to be able to turn every link (http://*.*) and usernames (@.) into links. What would the regex for both of these be, and how would I implement it?

like image 784
Ethan Turkeltaub Avatar asked Dec 31 '10 16:12

Ethan Turkeltaub


People also ask

How do I turn a URL into a link?

Create a hyperlink to a location on the webSelect the text or picture that you want to display as a hyperlink. Press Ctrl+K. You can also right-click the text or picture and click Link on the shortcut menu. In the Insert Hyperlink box, type or paste your link in the Address box.

How do you turn a URL into a link in HTML?

To convert html to url press the "browse" button, then search and select the html file you need to convert. Press the green button "convert" and wait for your browser to download the url file that you have converted before.

How do I create an automatic hyperlink?

To link to a certain web page, you can simply type its URL in a cell, hit Enter, and Microsoft Excel will automatically convert the entry into a clickable hyperlink. To link to another worksheet or a specific location in another Excel file, you can use the Hyperlink context menu or Ctrl + K shortcut.


1 Answers

def link_urls_and_users s

    #regexps
    url = /( |^)http:\/\/([^\s]*\.[^\s]*)( |$)/
    user = /@(\w+)/

    #replace @usernames with links to that user
    while s =~ user
        s.sub! "@#{$1}", "<a href='http://twitter.com/#{$1}' >#{$1}</a>"
    end

    #replace urls with links
    while s =~ url
        name = $2
        s.sub! /( |^)http:\/\/#{name}( |$)/, " <a href='http://#{name}' >#{name}</a> "
    end

     s

end


puts link_urls_and_users(tweet.text)

This works, so long as URLs are padded by spaces or are at the beginning and/or end of the tweet.

like image 163
david4dev Avatar answered Oct 21 '22 07:10

david4dev