note 29626 added to function.preg-replace

From: Date: Wed, 19 Feb 2003 15:12:59 +0000
Subject: note 29626 added to function.preg-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-44206@lists.php.net to get a copy of this message
Yet another URL hyperlinking preg! - Finds all possible protocols: http ftp https chrome irc etc... - Ignores links which come after a = or " so href=", href= and the like are not linked - Finds URLs beginning with www. - Accepts all URL special chars, even rarely used ones like | , # ( or ) - Links URLs that are at the very beginning and/or end of a string. - Won't link ending . , ? ! etc. characters ie. http://www.someurl.com! becomes <a href="http://www.someurl.com">http://someurl.com</a>! function addLinks($string) { $string = preg_replace("/(^|[^=\"\/])\b((\w+:\/\/|www\.)[^\s<]+)". "((\W+|\b)([\s<]|$))/i", "$1<a href=\"$2\">$2</a>$4", $string); return preg_replace("/href=\"www/i", "href=\"http://www", $string); } Of course, like any URL linking preg, there are always ways to trip it up. In this case, if you end a URL with more than one . , ? or ! (like: http://www.someurl.com???) it will include all but the last one in the link. I'm sure there are other ways too... Enjoy, I hope :) Grey -- http://www.php.net/manual/en/function.preg-replace.php http://master.php.net/manage/user-notes.php?action=edit+29626 http://master.php.net/manage/user-notes.php?action=delete+29626 http://master.php.net/manage/user-notes.php?action=reject+29626

« previous php.notes (#44206) next »