Power of PHP: Reuse code with classes

Last time we looked at how PHP could be used to add hyperlinks to text URLs. Now this is something that could be really handy and that we might reuse over and over again. So let's save it as a class. For transparency this will be a separate file called livetext.php and it will be saved in a subfolder called 'classes'. This is what the class looks like in its entirety:
 <?php 
class liveText {

    function addHyperlinksToURLs ($data){ 
        $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); 
    } 
}

?>
It consists of a single function and this does all the work. So that's it for this class. Now when we want to use it, we first of all include it with the line:
include ("classes/livetext.php" );
We can then create a new instance of the class and send data to the function contained within it:
$textwithlinks=new liveText(); 
$textwithlinks->addHyperlinksToURLs($text);
It of course needs some data as well, and for simplicity we'll make that some static text here, so our whole file will look like this:
<?php 

include ("classes/livetext.php" );

$text ="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 or try Apple.com.";

$textwithlinks=new liveText(); 
$textwithlinks->addHyperlinksToURLs($text);
?> 

Comments