Power of PHP: Make live all web address URLs

I've been considering posting some PHP coding tips and tricks. Here's a little one to get things started. If it's popular then I'll follow up with some more in the New Year.

<?php
$data ="To learn more about programming iOS apps you can visit http://sketchytech.blogspot.com/2011/12/xcode-from-scratch-for-scaredy-cats.html directly or search for it on Google at www.google.com.";
$patterns = array('/(http:\/\/|https:\/\/)/','/([a-zA-Z0-9\-\.]+\.)(com|co.uk|org.uk|org|net|mil|edu|CO.UK|ORG.UK|COM|ORG|NET|MIL|EDU)(\/.[A-Za-z0-9\.&%\/-]{1,}|)/');
$replace = array('','<a href="http://\0">\0</a>');
echo preg_replace($patterns, $replace, $data);
?>
This code takes a variable $data, which can be changed to any text and then finds the URLs and converts them into hyperlinked text using preg_replace. It doesn't matter whether they begin http:// or www. but it isn't a complete implementation because various international extensions are missing, but hopefully it is enough to start breaking down the logic, which I'll explain more fully in the next post.


To test and run PHP on a Mac use BBEdit, HyperEdit, MAMP or similar. On a PC you can use a program like WampServer. If you're using Linux then I expect you'll be savvy enough to know what you're doing already. File should be saved as filename.php (where filename is whatever name you choose).



Comments