These two PHP functions use regular expressions to add the appropriate HTML anchor tags around hyperlinks and email addresses in $string.
PHP Code
function parseHyperlinks($string) {
// Add <a> tags around all hyperlinks in $string
return ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"\\0\">\\0</a>", $string);
}
function parseEmails($string) {
// Add <a> tags around all email addresses in $string
return ereg_replace("[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,3})", "<a href=\"mailto:\\0\">\\0</a>", $string);
}
Output
Using parseHyperlinks(), http://domain.com/index.htm becomes:
<a href="http://domain.com/index.htm">http://domain.com/index.htm</a>
And using parseEmails(), email@domain.com becomes:
<a href="mailto:email@domain.com">email@domain.com></a>
This doesn’t correctly parse e-mail addresses with mixed character case, i.e. myEmail@domain.com.
Gavin, good catch. I adjusted the regex to support both upper and lowercase.
thank you very much. beautifuly code and very useful. will use both functions in my twitter-plugin for wordpress, which I will release in the next few days. needless to say, I will mention you in the about-page and in the source code :) have a nice weekend and keep up the good work!
Thank you very much! I used this code for my website… http://www.myiptest.com
how can we do the reverse of this?? Can anybody help me into this?