Snippets v2

Languages
My Snippets

Truncate a long string and add Ellipsis Login or Register to Bookmark this snippet

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 Contact JC

Added by JC on 14th January, 2008

Comments

There are no comments about this snippet.

Post Comment HTML is allowed

You must be registered and logged in to post a comment.

Login here to post a comment