Shorten text values without to break words

There are several situations were a shorter text version on your website is necessary: Post summaries for result pages or just for the page’s META description (of course it’s better to write a unique description). The regular PHP function “substr()” will shorten your text to a given length without a check if the text will end in a middle of a word.

I’m using this custom PHP function to shorten my text blocks on most of my non-WordPress websites:

function create_short_version($text, $len = 150, $more = '...') {
	$parts = explode(' ', $text);
	$ic = count($parts);
	$txt = '';
	for ($i = 0; $i < $ic; $i++) {
		$txt .= $parts[$i].' ';
		if (strlen($txt) >= $len) break;
	}
	$txt = trim($txt);
	if (strlen($text) > $len) $txt .= $more;
	return $txt;
}

The function works like the sub_str() function in PHP, but without to break all the words in pieces. The value for the $length is the maximum number of characters the function can return (it depends on the length of the last checked word).

4 thoughts on “Shorten text values without to break words”

    1. Hi,
      This function will break up words too, according the PHP manual:

      echo mb_strimwidth("Hello World", 0, 10, "...");
      // outputs Hello W...

      Btw. I replaced your reference link with the one from php.net, most people can read English ;)

  1. For your WordPress theme or plugin is the function called wp_trim_words() very useful. The function works the same as the example code from this page, example:

    $content = get_the_content();
    $trimmed_content = wp_trim_words( $content, 40, ' ...Read More' );
    echo $trimmed_content;
    
    1. Thanks Peter, it’s always beter to use existing functions than using new code. I will add the link to the WordPress Codex for this function into your comment.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.