How to Convert URL’s in Text to Links Using PHP

The function below takes in a string of text and converts all URL’s that start with "http://" to an HTML link.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
 * Returns the string with URL's replaced with actual HTML link tags
 * @param string $string The string to parse for URL's
 * @param boolean $noFollow Whether or not to add the rel="nofollow" 
 * attribute to the tag
 * @param boolean $newWindow Whether or not to make the link open in a new
 * window
 * @return string
 */
function getStringWithUrlLinks($string, $noFollow = true, $newWindow = true)
{
	$pattern = '/(http:\/\/[^\s]+)/';
	return preg_replace_callback($pattern,
		create_function('$matches',
			'return \'<a href="\'.$matches[0].\'" '
			. (($noFollow) ? ' rel="nofollow"' : '')
			. (($newWindow) ? ' target="_blank"' : '')
			. '>\'.$matches[0].\'</a>\';'
		), $string);
}

Here is an example usage:

21
22
23
$string = 'This is my website: http://www.jesterwebster.com/';
$stringHtml = nl2br(getStringWithUrlLinks(htmlentities($string)));
echo $stringHtml;

The example above would output:
This is my website: http://www.jesterwebster.com/

One Response

Leave a Reply

*