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...

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie