I\'m pulling blog posts from a DB. I want to trim the text to a max length of 340 characters.
If the blog post is over 340 characters I want to trim the text to the las
function trim_characters( $text, $length = 340 ) {
$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 );
}
return $text;
}
Use this function trim_characters() to trims a string of words to a specified number of characters, gracefully stopping at white spaces. I think this is helpful to you.