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).

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Add to favorites
  • Design Float
  • DZone
  • email
  • FriendFeed
  • PDF
  • Propeller
  • Reddit
  • RSS
  • StumbleUpon
  • Twitter

Related posts:

  1. Creating an Accordion using JQuery
  2. Creating a Simple Tooltip jQuery Plugin
  3. Creating a 3D carousel from scratch
  4. Create URL Shortener For Twitter Using PHP
  5. Really Simple Model/View Seperation With PHP


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!