Posted By

gauravjassal on 12/16/08


Tagged

sentence ellipsistrim


Versions (?)

Creating an Ellipsis in PHP


 / Published in: PHP
 

  1. <?php
  2. function ellipsis($text, $maxChars = 20, $splitter = '...')
  3. {
  4. $theReturn = $text;
  5. $lastSpace = false;
  6.  
  7. if (strlen($text) > $maxChars)
  8. {
  9. $theReturn = substr($text, 0, $maxChars - 1);
  10.  
  11. if (in_array(substr($text, $maxChars - 1, 1),array(' ', '.', '!', '?')))
  12. {
  13. $theReturn .= substr($text, $maxChars, 1);
  14. }
  15. else
  16. {
  17. $theReturn = substr($theReturn, 0, $maxChars - strlen($splitter));
  18. $lastSpace = strrpos($theReturn, ' ');
  19.  
  20. if ($lastSpace !== false)
  21. {
  22. $theReturn = substr($theReturn, 0, $lastSpace);
  23. }
  24.  
  25. if (in_array(substr($theReturn, -1, 1), array(',')))
  26. {
  27. $theReturn = substr($theReturn, 0, -1);
  28. }
  29. $theReturn .= $splitter;
  30. }
  31. }
  32. return $theReturn;
  33. }
  34. ?>
  35.  
  36. <?php
  37. $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.";
  38. echo ellipsis($text,150);
  39. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: Frank on December 16, 2008

why not use

string wordwrap ( string $str [, int $width [, string $break [, bool $cut ]]] )

You need to login to post a comment.