Return to Snippet

Revision: 48912
at July 12, 2011 22:37 by plesh


Initial Code
function replace_links( $text ) 
{	
	$text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $text);

	$ret = ' ' . $text;
	
	// Replace Links with http://
	$ret = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"\\2\" target=\"_blank\" rel=\"nofollow\">\\2</a>", $ret);
	
	// Replace Links without http://
	$ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*)#is", "\\1<a href=\"http://\\2\" target=\"_blank\" rel=\"nofollow\">\\2</a>", $ret);

	// Replace Email Addresses
	$ret = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $ret);
	$ret = substr($ret, 1);
	
	return $ret;
}

Initial URL
http://www.apashley.co.uk/snippets/40/Replace-Urls-With-Links--Php.html

Initial Description
A really handy snippet that will replace textual URLs with HTML links.

Also works for email addresses.

Initial Title
Replace URLs with links - PHP

Initial Tags
regex, php

Initial Language
PHP