Active Clickable Link Function preg_replace Programming Tutorial

Published :
Author :
Adam Khoury
Learn to use preg_replace() and regular expression arrays to automatically turn all URL strings in data into active clickable links. Most of the time the string is run through the function on the way out of the database for rendering on a page. After you put it into place on your site, your function or class will automatically turn URL strings found in written data into active clickable links. <?php // This function can be externally included as a dynamic reusable module function activateUrlStrings($str){ $find = array('`((?:https?|ftp)://\S+[[:alnum:]]/?)`si', '`((?<!//)(www\.\S+[[:alnum:]]/?))`si'); $replace = array('<a href="$1" target="_blank">$1</a>', '<a href="http://$1" target="_blank">$1</a>'); return preg_replace($find,$replace,$str); } // This is the code that calls the function to run $string = "my website is http://www.developphp.com and another website is www.youtube.com"; $string = activateUrlStrings($string); echo $string; ?>