PHP: Auto-hyperlink URLs with regex.

Posted on January 9, 2012 by Jimmy K. in Tutorials.

Have you ever typed a URL into an email or website and a clickable hyperlink was automagically created? Regular expressions, baby! Check it out:

<?php

/* auto-hyperlink urls */
function jAutoHyperlinkURLs($sInput, $sTarget = "_blank", $sClassName = "") {
	return preg_replace("/\\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]/i", "<a href=\"\\0\" target=\"$sTarget\" class=\"$sClassName\">\\0</a>", $sInput);
}

?>

This function accepts three arguments; $sInput, $sTarget (optional), and $sClassName (optional). $sInput is the text you would like to search and create hyperlinks for, $sTarget is the target window that hyperlinks will open in (_blank, _parent, _self, for example), and $sClassName is the CSS class name you would like to use for any hyperlinks that are created.

For example, “I found a great article using http://www.google.com!” will become “I found a great article using http://www.google.com!”

Tags: ,

 
 
 

If you like this, please leave a comment.