note 39908 deleted from function.preg-replace by aidan

From: Date: Sun, 05 Dec 2004 15:17:55 +0000
Subject: note 39908 deleted from function.preg-replace by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-81406@lists.php.net to get a copy of this message
Note Submitter: cgamedude at yahoo dot com ---- 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 ); }

« previous php.notes (#81406) next »