PHP - Make URLs clickable (And short down)
18
This function makes URLs in a given text clickable, and shorts down the link text if it's length is over the specified one. (Like vBulletin, etc... does)
PS:
Please explain negative votes, they're pointless otherwise...
PS:
Please explain negative votes, they're pointless otherwise...
<?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;
}






function parse_urls($text, $maxurl_len = 35, $target = '_self', $only_short_down = false)
{
if (!$only_short_down)
{
return preg_replace('/((ht|f)tps?:\/\/[^\s\r\n\t<>"\'\!\(\)]+)/ie', "'<a href=\"$1\" title=\"$1\" target=\"$target\">'. parse_urls(\"$1\", $maxurl_len, $target, true) .'</a>'", $text);
}
if ($maxurl_len AND strlen($text) > $maxurl_len)
{
$offset1 = ceil(0.65 * $maxurl_len) - 2;
$offset2 = ceil(0.30 * $maxurl_len) - 1;
$text = substr($text, 0, $offset1) . '...' . substr($text, -$offset2);
}
return $text;
}
Just replace the old pattern with this one:
'/(?<!href=["\'])((ht|f)tps?:\/\/[^\s\r\n\t<>"\'\!\(\)]+)/ie'