Skip to content

Instantly share code, notes, and snippets.

@alexanderdejong
Created December 20, 2017 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexanderdejong/71131e66b6f402df8dc6608f1c06119f to your computer and use it in GitHub Desktop.
Save alexanderdejong/71131e66b6f402df8dc6608f1c06119f to your computer and use it in GitHub Desktop.
Trim a string in WordPress to a specified number of characters, gracefully stopping at white spaces.
/**
* Trims a string of words to a specified number of characters, gracefully stopping at white spaces.
* Also strips HTML tags, to prevent breaking in the middle of a tag.
*
* @param string $text The string of words to be trimmed.
* @param int $length Maximum number of characters; defaults to 45.
* @param string $append String to append to end, when trimmed; defaults to ellipsis.
*
* @return String of words trimmed at specified character length.
*
* @author c.bavota
*/
function trim_characters( $text, $length = 45, $append = '…' ) {
$length = (int) $length;
$text = trim( strip_tags( $text ) );
if ( strlen( $text ) > $length ) {
$text = substr( $text, 0, $length + 1 );
$words = preg_split( "/[\s]| /", $text, -1, PREG_SPLIT_NO_EMPTY );
preg_match( "/[\s]| /", $text, $lastchar, 0, $length );
if ( empty( $lastchar ) )
array_pop( $words );
$text = implode( ' ', $words ) . $append;
}
return $text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment