Skip to content

Instantly share code, notes, and snippets.

@jonathanbardo
Last active December 15, 2015 19:19
Show Gist options
  • Save jonathanbardo/5310872 to your computer and use it in GitHub Desktop.
Save jonathanbardo/5310872 to your computer and use it in GitHub Desktop.
/**
* Trims text to a space then adds ellipses if desired
*
* @param string $input text to trim
* @param int $length in characters to trim to
* @param bool $ellipses if ellipses (...) are to be added
* @param bool $strip_html if html tags are to be stripped
* @return string
*/
function trim_text( $input, $length, $ellipses = true, $strip_html = true ) {
//strip tags, if desired
if ( $strip_html )
$input = strip_tags( $input );
//no need to trim, already shorter than trim length
if ( mb_strlen( $input ) <= $length )
return $input;
//find last space within length
$last_space = strrpos( substr($input, 0, $length), ' ' );
$trimmed_text = substr( $input, 0, $last_space );
//add ellipses (...)
if ( $ellipses )
$trimmed_text .= '...';
return $trimmed_text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment