Over a million developers have joined DZone.

Make URL's In Text Clickable

·
Ruby port of http://snippets.dzone.com/posts/show/6156 . Regexp's have been factored out into instance variables for efficiency when calling the linkify method more than once. Also, improved linkification of addresses that start with "ftp" (PHP version uses "http://" URL scheme for these instead of having a separate pass to apply the "ftp://" scheme).


@generic_URL_regexp = Regexp.new( '(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t<]*)', Regexp::MULTILINE | Regexp::IGNORECASE )
@starts_with_www_regexp = Regexp.new( '(^|[\n ])((www)\.[^ \"\t\n\r<]*)', Regexp::MULTILINE | Regexp::IGNORECASE )
@starts_with_ftp_regexp = Regexp.new( '(^|[\n ])((ftp)\.[^ \"\t\n\r<]*)', Regexp::MULTILINE | Regexp::IGNORECASE )
@email_regexp = Regexp.new( '(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)', Regexp::IGNORECASE )

def linkify( text )
  s = text.to_s
  s.gsub!( @generic_URL_regexp, '\1\2' )
  s.gsub!( @starts_with_www_regexp, '\1\2' )
  s.gsub!( @starts_with_ftp_regexp, '\1\2' )
  s.gsub!( @email_regexp, '\1\2@\3' )
  s
end
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}