note 82020 deleted from function.preg-replace by danbrown
| From: | danbrown@php.net | Date: | Mon, 20 Jun 2011 15:19:46 +0000 |
| Subject: | note 82020 deleted from function.preg-replace by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-180737@lists.php.net to get a copy of this message | ||
Note Submitter: Misha
----
This is in response to iasmin at amazingdiscoveries dot org's URL text to link function. Hope
this is helpful to someone.
I played with it a bit and came up with this version (there were one or two little errors in the
regex I think, also -- it didn't allow various necessary characters).
I start with a URL in brackets (this works for my case):
[http://www.site.com/path/that/may/be_long.php?fun=1]
It returns a link of the URL after the "http://":
www.site.com/path/that/may/b...
-----------
// Cuts off long URLs at $url_length, and appends "..."
function reduceurl($url, $url_length) {
$reduced_url = substr($url, 0, $url_length);
if (strlen($url) > $url_length) $reduced_url .= '...';
return $reduced_url;
}
// Makes URLs with brackets into links
// The regex searches for "http://" or equivalent, then
various character possibilities (I don't know if it might be possible to exploit this if more
characters were allowed). The "e" after the regex allows the reduceurl() to be evaluated.
function url2link($linktext) {
$linktext = preg_replace("#\[(([a-zA-Z]+://)([a-zA-Z0-9?&%.;:/=+_-]*))\]#e",
"'<a href=\"$1\" target=\"_blank\">' .
reduceurl(\"$3\", 30) . '</a>'", $linktext);
return $linktext;
}