Pages

Truncate and break at word

This will attempt to shorten a string to $length characters, but will then increase the string (if necessary) to break at the next whole word and then append an ellipses to the end of the string. Good for shortening readable text while keeping it looking pretty.
function truncate($string, $length) {
    if (strlen($string) > $length) {
        $pos = strpos($string, " ", $length);
        return substr($string, 0, $pos) . "...";
    }
    return $string;
}
Use :
echo truncate('In the above example, the resultant output will be the quick brown…, because the 10th character is the space immediately before the ‘b’ in ‘brown’, which is counted as part of the word ‘brown’.', 100);