Limiting Text
When I was figuring out how to present the 5 random websites off GIDTopsites™, I decided to limit the site description to a certain length so that it will fit better on these pages. I wrote a little function in PHP that does that for me PLUS I made sure that I could re-use it in future scripts that I may come up with.
The main 'engine' behind this script is the PHP function substr() which is simply powerful when you want to return a portion of a string or text. In the function I wrote below, I added a line to remove the last incomplete word in the returned portion of text.
A function to limit text
Of course you can also copy this code and use it freely in the scripts that you may write.
<?php
function limit_text( $text, $limit )
{
// figure out the total length of the string
if( strlen($text)>$limit )
{
# cut the text
$text = substr( $text,0,$limit );
# lose any incomplete word at the end
$text = substr( $text,0,-(strlen(strrchr($text,' '))) );
}
// return the processed string
return $text;
}
?>
How do I use this function?
Now to use it, you'll just have to paste the function above, into your script or onto a 'includes' file (containing all your functions) if you prefer.
Let's assume you want to paste it with your script - so, this is what you could do:
<?php
// Filename: test.php
// ==================
// Our sample text
$long = 'Offers a discussion board, news portal, '
.'web-related articles, tutorials, scripts,'
.' tech blog, photo gallery, oekaki drawing,'
.' fun games, and more.';
// we only want the text to be 15 characters long.
$short15 = limit_text( $long,15 );
// perhaps we need one with just 6 characters.
$short06 = limit_text( $long,6 );
// we output some text
echo "<p>$long</p>\n";
echo "<p>$short15</p>\n";
echo "<p>$short06</p>\n";
// ============================================
// now we paste our LIMIT_TEXT() function below
// ============================================
function limit_text( $text, $limit )
{
if( strlen($text)>$limit )
{
$text = substr( $text,0,$limit );
$text = substr( $text,0,-(strlen(strrchr($text,' '))) );
}
return $text;
}
?>
Of course you can now add some endings to your echo statements so that your readers will know that there's more...
