note 46739 modified in function.preg-replace by aidan

From: Date: Thu, 04 Nov 2004 05:03:48 +0000
Subject: note 46739 modified in function.preg-replace by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-79580@lists.php.net to get a copy of this message
I needed to treat exclusively long urls and not shorter ones for which my client prefered to have their complete addresses displayed. Here's the function I end up with: <?php function auto_url($txt){ # (1) catch those with url larger than 71 characters $pat = '/(http|ftp)+(?:s)?:(\\/\\/)' .'((\\w|\\.)+)(\\/)?(\\S){71,}/i'; $txt = preg_replace($pat, "<a href=\"\\0\" target=\"_blank\">$1$2$3/...</a>", $txt); # (2) replace the other short urls provided that they are not contained inside an html tag already. $pat = '/(?<!href=\")(http|ftp)+(s)?:' . .'(\\/\\/)((\\w|\\.)+) (\\/)?(\\S)/i'; $txt = preg_replace($pat,"<a href=\"$0\" target=\"_blank\">$0</a> ", $txt); return $txt; } ?> Note the negative look behind expression added in the second instance for exempting those that are preceded with ' href=" ' (meaning that they were already put inside appropiate html tags by the previous expression) (get rid of the space between question mark and the last parenthesis group in both regex, I need to put it like that to be able to post this comment) --was-- I needed to treat exclusively long urls and not shorter ones for which my client prefered to have their complete addresses displayed. Here's the function I end up with: <?php function auto_url($txt){ # (1) catch those with url larger than 71 characters $txt = preg_replace("/(http|ftp)+(?:s)?:(\\/\\/)((\\w|\\.)+)(\\/)? (\\S){71,}/i", "<a href=\"\\0\" target=\"_blank\">$1$2$3/...</a>", $txt ); # (2) replace the other short urls provided that they are not contained inside an html tag already. $txt = preg_replace( "/(?<!href=\")(http|ftp)+(s)?:(\\/\\/)((\\w|\\.)+) (\\/)?(\\S)/i","<a href=\"$0\" target=\"_blank\">$0</a> ", $txt ); return $txt; } ?> Note the negative look behind expression added in the second instance for exempting those that are preceded with ' href=" ' (meaning that they were already put inside appropiate html tags by the previous expression) (get rid of the space between question mark and the last parenthesis group in both regex, I need to put it like that to be able to post this comment) http://php.net/manual/en/function.preg-replace.php

« previous php.notes (#79580) next »