Collapsing Link Titles
Let's assume, you are creating a PHP script that will allow users to submit a URL to the database in your script. Most likely, you're allowing your readers to post a URL in a forum message or post or in a guestbook script. This means that sometimes whole URLs are inserted and some of these URLs can be extremely long, especially if they're 'copied n pasted'.
Sample long URL
http://www.example.com/index.php?nav=main&cat=201&kw=whatever&language=EN&submit=verified
That's one long URL, right? If you're like me, you'd probably want your script to handle 'trimming' this long URL and present it like this:
http://www.example.com/index.p...t=verified
instead of
http://www.example.com/index.php?nav=main&cat=201&kw=whatever&language=EN&submit=verified
Function : trim_link()
I wrote this function for my scripts to handle doing just this and I have copied it here for you to copy and use freely in your own scripts.
<?php
function trim_link( $link, $limit=60 )
{
if( $limit>39 )
// we test the limit that it's at least 39 characters,
// otherwise our presentation will look awkward!
{
// figure out the total length of the link title
if( strlen($link)>$limit )
{
// edit the link
// we also return the last 10 characters of the long
// URL i.e. the '-10' value in the line below
$link = substr( $link,0,($limit/2) ).'...'.substr($link,-10);
}
}
// return the processed string
return $link;
}
?>
Sample use of this function; trim_link()
Here's a sample page where we use this function for our URL presentation:
<?php
// Filename:test.php
$url = 'http://www.example.org/index.php?cat=webdsn&
sec=apache&page=php&lang=EN&title=whatever';
// Echo our links but 'collapse' any url that's longer than
// 44 characters.
echo '44 = <a href="'.$url.'" target="_blank">'.trim_link($url,44).'</a>';
// or echo our link but 'collapse' any url that's longer than
// the default value i.e. 60 characters.
echo '60 = <a href="'.$url.'" target="_blank">'.trim_link($url).'</a>';
// ===================================
// FUNCTION TRIM_LINK()
// ===================================
function trim_link( $link, $limit=60 )
{
if( $limit>39 )
{
if( strlen($link)>$limit )
{
$link = substr( $link,0,($limit/2) ).'...'.substr($link,-10);
}
}
return $link;
}
?>
Now if we run our test.php page, we should get the following results:
44 = http://www.example.org...e=whatever
60 = http://www.example.org/index.p...e=whatever
