note 46739 added to function.preg-replace
| From: | ignaciopazposse at osu1 dot php dot net | Date: | Thu, 21 Oct 2004 20:22:49 +0000 |
| Subject: | note 46739 added to function.preg-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-78904@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
$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)
----
Manual Page -- http://www.php.net/manual/en/function.preg-replace.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+46739
Delete -- http://master.php.net/manage/user-notes.php?action=delete+46739&report=yes
Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+46739&report=yes&reason=bad+code
Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+46739&report=yes&reason=spam
Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+46739&report=yes&reason=useless+example
Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+46739&report=yes&reason=contains+commercial+links
Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+46739&report=yes&reason=useless+note
Reject -- http://master.php.net/manage/user-notes.php?action=reject+46739&report=yes
Search -- http://master.php.net/manage/user-notes.php