Turn Plain Text URLs into Active Links using PHP
by c.bavota | Posted in Tutorials | 10 comments
Sep 03 2009
I was putting together a bit of code to pull in a Twitter feed, similar to what you see in the footer of bavotasan.com. I got everything working properly but the only problem was all of the URLs were just plain text instead of active links. I figured out a way to automatically turn the URLs into active links using a small piece of PHP.
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href=\"\\0\">\\0</a>", $text);
The code finds all instances of http:// and converts the string into an active link by surrounding it with an anchor tag.



Chris, just as a way to help some of the non-technical people out there you could wrap this code in a simple function and make it a lot easier for them.
function HyperlinkText($text) {return ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"\\">\</a>", $text);
}
If people put this function in the bottom of their PHP file, they can now simply call it throughout the code by typing:
echo HyperlinkText("Your http://thisismyurl.com here.");Thx. Great tip.
Cool.. But I’ve noticed, that this will not work, if the URL contains parameters.
Ex:
http://macknonalds.0fees.net/index.php?para=1¶=2
Do you have any idea, on how to properly place regex, to accommodate this kind of URL inputs?
Thanks
I know you are showing a general way to do this for any PHP project, but thought people might want to know the best way to do this in WordPress specfically. There is a function called make_clickable() that you can use. http://codex.wordpress.org/Function_Reference/make_clickable
Actually, in WordPress 2.9 there is an option to automatically embed all plain text URLs. Check out the Media admin page under the Settings panel.
Nice, thanks. Hadn’t noticed that new option. I don’t want to take this off topic too far, but do you have a good replace function to force external URL’s to open in a new browser tab? i.e. find all the URL’s and check whether they already have a target=”" parm on them and if not set target=”whatever”?
There is a plugin I have used in the past called Zap New Window. I don’t know how well it has been maintained though.
http://www.zappelfillip.de/2005-12-05/zap_newwindow/
Great tip, thanks!