Trim a String Without Cutting Any Words


Sometimes you need to trim a string without cutting any word.

In PHP there is no any function for that but this function may help you.


function trim_sentence($str, $n, $delim='...'){
$len = strlen($str);
if ($len > $n){
preg_match('/(.{' . $n . '}.*?)\b/', $str, $matches);
return rtrim($matches[1]) . $delim;
}
else {
return $str;
}
}

Advertisements