Created
December 20, 2017 14:41
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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