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:

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

{{ parent.tldr }}

{{ parent.urlSource.name }}