PHP Teaser String

While you're parsing text for display, it's often useful to shorten it down to blurbs - without cutting off mid-word.


/**
 * Shorten a string for teaser
 *
 * @param   (string)  $str    - string to work on
 * @param   (int)     $len    - maximum string length
 *
 * @return  (string)
 **/
function ShortenString( $str, $len = 200 )
{
  if( !is_string( $str ) || !is_numeric( $len ) ) return $str;
  $str = strip_tags( $str );
  if( strlen( $str ) > $len )
  {
    $str = substr( $str, 0, $len );
    $str = substr( $str, 0, strrpos( $str, ' ' ) ) . '...';
  }
  return $str;
}
Top