Shorten string without cutting words

function txtShortener($string, $length, $replacer) { if(strlen($string) > $length) return (preg_match('/^(.*)\W.*$/', substr($string, 0, $length+1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer; return $string; } // Usage example: $shrtr = txtShortener('More than five words string goes here.', 5,'...'); // Only 5 words will be shown and then ...
Stop dealing with long excerpts or using css tricks to make it show nicely, adjust the length of the text so it never overflows again.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.