Trim Characters using PHP

I had previously written about how you can easily trim your text using a build in WordPress function called wp_trim_words() but sometimes you actually want to trim your text to a specific number of characters as opposed to actual words. Here is a short function that will do just that. If you want to use it in a WordPress theme, just place it within the PHP tags in your functions.php file.
/**
 * 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;
}
With the function in place, you can use something similar to the following to trim your text strings:
$string = "This is a string of text that I want to trim down to a specific number of characters.";
trim_characters( $string ); // Output: This is a string of text that I want to trim...
Search

Popular Posts

Small Biz Website Tips Newsletter

Stay up to date with the latest marketing, sales, and service tips and news.

Small Biz Website Tips Newsletter

Stay up to date with the latest marketing, sales, and service tips and news.