Creating an Ellipsis in PHP

 

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='&hellip;')
{
	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).

Be Sociable, Share!

Written by Brenley Dueck

 

3 Responses to “Creating an Ellipsis in PHP”

  1. Luke Sutton Says:

    December 14th, 2008 at 2:34 am

    FYI, three periods are not an ellipsis.

    This is:

  2. RantingJerk Says:

    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;
    }

  3. admin Says:

    December 16th, 2008 at 2:53 pm

    I have added your code above RantingJerk. Thanks for the input!

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 
connect with me!