Truncate a long string and add Ellipsis

Description PHP

This function will truncate a string to a certain length. By default it will stop on a word.

The Code Download

  1. <?php
  2. function Truncate($string, $length, $stopanywhere=false) {
  3.     //truncates a string to a certain char length, stopping on a word if not specified otherwise.
  4.     if (strlen($string) > $length) {
  5.         //limit hit!
  6.         $string = substr($string,0,($length -3));
  7.         if ($stopanywhere) {
  8.             //stop anywhere
  9.             $string .= '...';
  10.         } else{
  11.             //stop on a word.
  12.             $string = substr($string,0,strrpos($string,' ')).'...';
  13.         }
  14.     }
  15.     return $string;
  16. }
  17. ?>

Credits

Added by JC on 14th January 2008

Comments

There are no comments about this snippet.

Post Comment Github Markdown Supported

You must be logged in to post a comment.

Login here to post a comment