submitted by: Guest

PHP: Truncate String Function

This function uses strlen() to truncate a long string and return a shortened version.


code snippet:
<?php

function Truncate ($str$length=10$trailing='...'
{
      
// take off chars for the trailing
      
$length-=strlen($trailing);
      if (
strlen($str) > $length
      {
         
// string exceeded length, truncate and add trailing dots
         
return substr($str,0,$length).$trailing;
      } 
      else 
      { 
         
// string was already short enough, return the string
         
$res $str
      }
  
      return 
$res;
}

?>

notes:
This handy function was written by Jerret Taylor, more can be found at his site at: http://jerrett.liquidpulse.net