Return to Snippet

Revision: 47683
at June 13, 2011 21:58 by nebojsac


Initial Code
function activateLinks($string)
{  
 /*
	// This regular expression looks for <strong>http:// </strong>type url
	$string = preg_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)',
	'<a href="1" target=_blank>$0$1$2$3</a>', $string);
	 
	// This regular expression looks for <strong>www. </strong>type url
	$string = preg_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)',
	'1<a href="http://2" target=_blank>$0$1$2$3</a>', $string);
	 
	// This regular expression looks for <strong>[email protected]</strong>
	$string = preg_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})',
	'<a href="mailto:1" target=_blank>$0$1$2$3</a>', $string);
	 */
	 
	 $m = preg_match_all('/http:\/\/[a-z0-9A-Z.]+(?(?=[\/])(.*))/', $string, $match); 

	 if ($m) { 
		 $links=$match[0]; 
		 for ($j=0;$j<$m;$j++) { 
			 $string=str_replace($links[$j],'<a href="'.$links[$j].'">'.$links[$j].'</a>',$string); 
		 } 
	 }
	 
	 $m = preg_match_all('(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)', $string, $match); 

	 if ($m) { 
		 $links=$match[0]; 
		 for ($j=0;$j<$m;$j++) { 
			 $string=str_replace($links[$j],'<a href="'.$links[$j].'">'.$links[$j].'</a>',$string); 
		 } 
	 }
	 
	return $string;
	 
}

Initial URL
http://www.php.net/manual/en/function.preg-match-all.php#103552

Initial Description
Returns the same string, except with links wrapped in <a href=""> tags. Works on www.snipplr.com and on http://snipplr.com

A variation of the script on the attached URL.

Initial Title
Activate Links in String PHP

Initial Tags
regex, php, links

Initial Language
PHP