Truncate Links Over X Chars Long

Description: Truncate URL if longer than ‘X’ characters (add http:// or ftp:// if missing)

<?PHP
 
FUNCTION handle_url_tag($url, $link = ''){
     GLOBAL $FORUM_user;
 
     // maximum link length
     $MAXLEN = 50;
 
     // if too long, clip it to how many chars?
     $CLIPTO = 45;
 
     $full_url = STR_REPLACE(ARRAY(' ', '\'', '`', '"'), array('%20', '', '', ''), $url);
     if (strpos($url, 'www.') === 0)               // If it starts with www, we add http://
          $full_url = 'http://'.$full_url;
     else if (strpos($url, 'ftp.') === 0)     // Else if it starts with ftp, we add ftp://
          $full_url = 'ftp://'.$full_url;
     else if (!preg_match('#^([a-z0-9]{3,6})://#', $url, $bah))      // Else if it doesn't start with abcdef://, we add http://
          $full_url = 'http://'.$full_url;
 
     // Ok, not very pretty :-)
     $link = ($link == '' || $link == $url) ? ((strlen($url) > $MAXLEN) ? substr($url, 0 , $CLIPTO).' � '.substr($url, -10) : $url) : stripslashes($link);
 
     return '<a href="'.$full_url.'">'.$link.'</a>';
}
 
?>

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.