The following is a function that I use for when I need to create a sampling of text and I really like it. Some features it has is it only breaks at a space, and allows total customization of the max characters and the cut-off text. See the below:
Note: Thanks to RantingJerk for commenting on a neater version of the following then I previously had!
< ?php
function ellipsis($text, $max=100, $append='…')
{
if (strlen($text) <= $max) return $text;
$out = substr($text,0,$max);
if (strpos($text,' ') === FALSE) return $out.$append;
return preg_replace('/\w+$/','',$out).$append;
}
?>
This function can then be used in the following way:
< ?php $text = "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo."; echo ellipsis($text,100); ?>
I hope this little trick helps you speed up your development time! Have any utility functions you keep around? Comment Below or tweet me (@brenelz).
December 14th, 2008 at 2:34 am
FYI, three periods are not an ellipsis.
This is:
…
December 14th, 2008 at 9:56 pm
I saw this and couldn’t help but say to myself “goddamn thats a bunch of cruft”,
function ellipsis($text, $max=100, $append=’&elip;’)
{
if (strlen($text) <= $max) return $text;
$out = substr($text,0,$max);
if (strpos($text,’ ‘) === FALSE) return $out.$append;
return preg_replace(‘/\w+$/’,”,$out).$append;
}
December 16th, 2008 at 2:53 pm
I have added your code above RantingJerk. Thanks for the input!
Twitter
Follow me on Twitter to keep up to date!
RSS Feed
Keep up with all of our updates by subscribing to our RSS feed!
FaceBook
Join our group on Facebook and become a fan of us!