PHP - Make URLs clickable (And short down)





18
Date Submitted Wed. Feb. 28th, 2007 12:30 PM
Revision 1 of 1
Helper Nico
Tags clickable | PHP | URL
Comments 2 comments
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...


<?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;
} 

 

Nico Oelgart

www.nicoswd.com

Comments

Comments Revision
Fri. Mar. 9th, 2007 4:33 AM    Helper Nico
Comments 2nd Revision
Wed. Apr. 4th, 2007 7:58 AM    Helper Nico

Voting