Truncate Strings by Length, Word Count

Use this function to limit or truncate a string to a specified number of characters or word count, or both. In the case of defining both criteria, the word count is applied first then the character length is applied. Paste the following code into your Functions page (and be sure to load it before you attempt to call it from your code) or on the page you use this function.

/**
 * @function: $Id: tah_truncate_string 2011-03-10 21:32:12P $EXP
 * @input:    $string String to be modified
 * @input:    [;$numchars Final maximum String Length,] default 0
 * @input:    [;$numwords Final Word Count,] default 0
 * @return:   Modified String
 * @author:   Chris Anderson — c h r i s @ c l a b s c o . c o m
 * @author URL: http://www.clabsco.com
 */

function tah_truncate_string( $string, $numchars = 0, $numwords = 0 )
{
     // Always capture input to another variable before manipulating it
     // Split the variable into an array
     $str = explode( " ", $string, $numwords );
     // First apply the word count
     if ( $numwords && count($str) >= $numwords ) {
         // Pop the last element off the end (overlimit string)
         array_pop( $str );
         $str = implode( " ", $str );
         // This is where you indicate ellipsis is needed
     }
     else {
         $str = implode( " ", $str );
     }

     // Now apply the character count
     $len = strlen( " ", $str );
     if ( $numchars && $len > $numchars ) {
         // remove the excess characters
         $str = substr( $str, 0, $numchars );
         $str = explode( " ", $str );
         // Pop the last word or partial word off the end
         array_pop( $str );
         $str = implode( " ", $str );
         // Indicate an ellipsis is needed
     }
     // Code to add an ellipsis if indicated
 
     // exit the function when you get here
     return $str;
}
Note
  • This function does not add an ellipsis (those three little dots …) or any other character to the end of the string, though you could easily modify it to do so.
Back to Top

The Anderson Home