note 39908 added to function.preg-replace

From: Date: Sun, 15 Feb 2004 08:15:44 +0000
Subject: note 39908 added to function.preg-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-65158@lists.php.net to get a copy of this message
I wrote a function to convert URLs *that are not already in anchor tags* into hyperlinks. It works with both http://blah.com and www.blah.com and I tried to make it actually understandable by not using a single 200-char expression :) It's used like: $Text = InsertLinks( $Text ); Anyway here it is: function InsertLinks ( $Text ) { // First match things beginning with http:// (or other protocols) $NotAnchor = '(?<!"|href=|href\s=\s|href=\s|href\s=)'; $Protocol = '(http|ftp|https):\/\/'; $Domain = '[\w]+(.[\w]+)'; $Subdir = '([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?'; $Expr = '/' . $NotAnchor . $Protocol . $Domain . $Subdir . '/i'; $Result = preg_replace( $Expr, "<a href=\"$0\" title=\"$0\" target=\"_blank\">$0</a>", $Text ); // Now match things beginning with www. $NotAnchor = '(?<!"|href=|href\s=\s|href=\s|href\s=)'; $NotHTTP = '(?<!:\/\/)'; $Domain = 'www(.[\w]+)'; $Subdir = '([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?'; $Expr = '/' . $NotAnchor . $NotHTTP . $Domain . $Subdir . '/i'; return preg_replace( $Expr, "<a href=\"http://$0\" title=\"http://$0\" target=\"_blank\">$0</a>", $Result ); } ---- Manual Page -- http://www.php.net/manual/en/function.preg-replace.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+39908 Delete -- http://master.php.net/manage/user-notes.php?action=delete+39908&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+39908&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#65158) next »