If you've ever found that you want to limit a string to a certain length and add an ellipsis (...) to it if it goes over that length, here is a useful little function for that:
PHP Code:
function ellipsis($string, $length){ if (strlen($string) > $length) { $string = substr($string, 0, $length).'...'; } return $string; }
I find it most useful for keeping information displayed in a table to a certain length so it doesn't mess up my layout. For instance, if you had a table that lists blog entries, you may want to use this on the title.
Usage
Both parameters are required for the function. - $string - the string to be shortened and to have an ellipsis added to
- $length - the length at which the string should be shortened and an ellipsis should be added
Example
Using our blog example above, here is how to use this function:
PHP Code:
$blogTitle = 'This is one example of a really long blog title that would normally probably be a dynamic entry'; $blogTitle2 = 'Short title';
echo ellipsis($blogTitle, 11); //Returns 'This is one...' echo ellipsis($blogTitle2, 11); //Returns 'Short title'
That's it. Nothing too fancy or spectacular, but hopefully useful to someone. If you can improve it, please do so and post your changes. Feel free to use it wherever you need it.
|