<?php
$text =
'Some text here with an URL here http://www.superlongurl.com/superlongfoldername/filename.ext and some more text here blah blah blah.';
/*
Makes the URLs clickable and shorts them down to 35 chars max since it's the default value and no other one was specified.
*/
echo parse_urls
($text);
/*
Outputs: Some text here with an URL here http://www.superlongurl.c...ilename.ext and some more text here blah blah blah.
*/
echo parse_urls
($text,
40);
/*
Makes the URLs clickable, but doesn't short them down.
*/
echo parse_urls
($text,
false);
/*
Makes the URLs clickable, and sets the target attribute to _blank, so they will open in a new window. This can be left in blank. The default target is _self.
*/
echo parse_urls
($text,
false,
'_blank');
?>
function parse_urls
($text,
$maxurl_len =
35,
$target =
'_self')
{
if (preg_match_all('/((ht|f)tps?:\/\/([\w\.]+\.)?[\w-]+(\.[a-zA-Z]{2,4})?[^\s\r\n\(\)"\'<>\,\!]+)/si',
$text,
$urls))
{
$offset1 =
ceil(0.65 *
$maxurl_len) -
2;
$offset2 =
ceil(0.30 *
$maxurl_len) -
1;
foreach (array_unique($urls[1]) AS $url)
{
if ($maxurl_len AND
strlen($url) >
$maxurl_len)
{
$urltext =
substr($url,
0,
$offset1) .
'...' .
substr($url, -
$offset2);
}
else
{
$urltext =
$url;
}
$text =
str_replace($url,
'<a href="'.
$url .
'" target="'.
$target .
'" title="'.
$url .
'">'.
$urltext .
'</a>',
$text);
}
}
return $text;
}