convert links into clickable hyperlinks with PHP
Thursday, April 1st, 2010 5 Comments
This function changes an email address or URL into a clickable HTML hyperlink using eregi_replace.
<?php
function makeClickableLink($text) {
$text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '<a href="\\1">\\1</a>', $text);
$text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '\\1<a href="http://\\2">\\2</a>', $text);
$text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})', '<a href="mailto:\\1">\\1</a>', $text);
return $text;
}
// Usage
// Email address example
$text = "you@example.com";
echo makeClickableLink($text);
// URL example
$text = "http://www.example.com";
echo makeClickableLink($text);
// FTP URL example
$text = "ftp://ftp.example.com";
echo makeClickableLink($text);
?>
It’s pretty self-explanatory at a high level, but when you delve into the regex it does get a bit baffling. Let me walk you through it.
The Explanation:
Step 1:
$text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '<a href="\\1">\\1</a>', $text);
The first eregi_replace checks whether the supplied string contains an ‘f’ or ‘ht’, followed by ‘tp://’ then a string of characters restricted to those allowed by W3 specifications. This string is then inserted into a link phrasing, both as the href and as the link text.
Step 2:
$text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '\\1<a href="http://\\2">\\2</a>', $text);
The second eregi_replace checks whether the supplied string begins with any spaces, then ‘www.’ followed by a string of characters restricted to those allowed by W3 specifications. The spaces clause is then inserted before a link phrasing, the string beginning ‘www.’ is then inserted in the link phrasing both as the href and as the link text preceded by ‘http://’. This overwrites $text.
Step 3:
$text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})', '<a href="mailto:\\1">\\1</a>', $text);
The third eregi_replace checks whether the supplied string begins with characters, is followed by an ‘@’ , followed by more characters, a full-stop, and then either 2 or 3 lower-case alpha characters. This again matches W3 specifications. This matched pattern is inserted into a string which formats it as a mailto link.
Pingback: The Official Clickable Blog | marketingformularevealed.com
I think you want to add that ; is Ok inside an URL. this can happen when the ampersand is correctly encoded as with the amp;. Here’s the tweak that I did:
$text = eregi_replace(‘(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=;]+)’, ‘\\1‘, $text);
$text = eregi_replace(‘(((f|ht){1}tps://)[-a-zA-Z0-9@:%_\+.~#?&//=;]+)’, ‘\\1‘, $text);
$text = eregi_replace(‘([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=;]+)’, ‘\\1\\2‘, $text);
not able to understand step 2
Thanks,This piece of code really helped me
Regards;
Nida
Pingback: format a url nicely in PHP « whileloop