faqts : Computers : Programming : Languages : PHP : Common Problems : Regular Expressions

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

71 of 82 people (87%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How can I turn all URL's in a string into working links?

Jul 2nd, 1999 07:45
Nathan Wallace, Michael Stearne


The following regular expression will replace all URL's in a string
($msg) with working links.

$msg = eregi_replace(
    "(http|https|ftp)://([[:alnum:]/\n+-=%&:_.~?]+[#[:alnum:]+]*)",
    "<a href=\"\\1://\\2\" target=\"_blank\">\\1://\\2</a>",
    $msg);

Note that this regular expression allows for URL's to extend over more
than one line (\n).  In some cases you might like to remove this
capability since if the URL finishes exactly at the end of a line and 
there are no spaces before the next word that word will be enabled.  For
example, "Enabled" below will be part of the links when \n is included. 
Line breaks are denoted with <CR>.

http://www.somewhere.com<CR>
<CR>
Enabled