hyperlinking URLs (and emails?) in text

R

Ruby Baby

Ugly:

class String
def hyperlink
gsub(/(http:\/\/|https:\/\/|mailto:)([[:alnum:]\/!\#$\%&'()*+,.:;=?@~-]+)([[:alnum:]\/!\#$\%&'()*+:;=?@~-])/, '<a href="\\1\\2\\3">\\1\\2\\3</a>')
end
end

... but it generally works, from my few tests.


Anyone got a better version, or care to improve on this one?

Just trying to hyperlink URLs in text (and in future, email addresses, without needing mailto:).
 
M

Mark Hubbart

This is a little bit more readable, while still being somewhat compact.
It also gets plain email addresses:

class String
def hyperlink
# define url parts:
chars = Regexp.escape "/!#$\\%&'()*+,.:;=?@~-_"
url = "https?:\\/\\/[#{chars}[:alnum:]]+"
email = "(?:mailto:)?[^\s@]+@[[:alnum:]._-]+\\.[[:alnum:]._-]+"
# do the substitution:
gsub(/#{url}|#{email}/) do |link|
if link =~ /^[a-zA-Z]+:/
%Q(<a href="#{link}">#{link}</a>)
else
%Q(<a href="mailto:#{link}">#{link}</a>)
end
end
end
end

Note that this will not get *all* email addresses, and it will let a
some urls spill through. But it should get most stuff. Getting it exact
would require more lines of code than I want to look at tonight :)
 
M

Minero Aoki

Hi,

In mail "hyperlinking URLs (and emails?) in text"
Ruby Baby said:
Anyone got a better version, or care to improve on this one?

Just trying to hyperlink URLs in text (and in future, email addresses, without needing mailto:).

If you have ruby 1.8.1:

require 'uri'

text.gsub(URI.regexp(%w(http https ftp))) {|urlstr|
%Q[<a href="#{urlstr}">#{urlstr}</a>]
}

Also, you will want to escape '<' '>' '&' in text:

require 'uri'
require 'cgi'

text.gsub(/[<&>"']|#{URI.regexp(%w(http https ftp))}/) {|matched|
case matched
when /[<&>"']/
CGI.escapeHTML(matched)
else
url = CGI.escapeHTML(matched)
%Q[<a href="#{url}">#{url}</a>]
end
}


Regards,
Minero Aoki
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top