[thelist] Re: [php] preg_replace text links?
Dunstan Orchard
dunstan at 1976design.com
Mon Nov 3 05:19:03 CST 2003
Hi Kris,
I use this code that Kelly gave to me:
function url_to_link($string)
{
// link URLs
$string =
eregi_replace("(([[:alnum:]]+://)|www\.)([^[:space:]]*)([[:alnum:]#?/&=])", "<a
href=\"\\1\\3\\4\" title=\"Go to \\1\\3\\4\">\\1\\3\\4</a>", $string);
// fix lazy URLs
$string = eregi_replace("href=\"www","href=\"http://www", $string);
// link mailtos
$string = eregi_replace("(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))",
"<a href=\"mailto:\\1\" title=\"E-mail \\1\">\\1</a>", $string);
// truncates long urls that can cause display problems
$string =
preg_replace("/>(([[:alnum:]]+:\/\/)|www\.)([^[:space:]]{30,40})([^[:space:]]*)([^[:space:]]{10,20})([[:alnum:]#?\/&=])</",
">\\1\\3...\\5\\6<", $string);
$string = stripslashes($string);
return $string;
}
I then altered it a bit so that I can print the person's name and link that to
the url they submitted (for my blog):
function url_to_link_poster($string, $name)
{
// link URLs
$string =
eregi_replace("(([[:alnum:]]+://)|www\.)([^[:space:]]*)([[:alnum:]#?/&=])", "<a
href=\"\\1\\3\\4\" title=\"Go to \\1\\3\\4\">$name</a>", $string);
// fix lazy URLs
$string = eregi_replace("href=\"www","href=\"http://www", $string);
$string = stripslashes($string);
return $string;
}
It's worked out perfectly for me for a while now.
HTH - Dunstan
---------------------------
Dorset, England
http://www.1976design.com/
http://www.1976design.com/blog/
More information about the thelist
mailing list