simple function to truncate string to closest word

as the title implies… this is in wordpress though. preg_replace is the trick here.

function trim_excerpt() {
$text = get_the_excerpt();
$limit = 200;
if (strlen($text) > $limit) {
$text =  preg_replace('/\s+?(\S+)?$/', '', substr($text, 0, $limit)).'... ';
return $text;

add_filter("the_excerpt", "trim_excerpt");

Author: bpeh

Bernard Peh is a great passioner of web technologies and one of the co-founder of Website Design and Reviews. He works with experienced web designers and developers everyday, developing and designing commercial websites. He specialises mainly in SEO and PHP programming.