Page 1 of 1

Shorten string and line breaks

Posted: Sat Dec 17, 2005 6:27 pm
by visionmaster
Hello,

Following function shortens a string to 350 characters, considering word boundaries. Chopping off in the middle of words is avoided.

Code: Select all

function strShortenText($strText, $length=350) {
    if (strlen($strText) > $length) {
        $pattern = '/^(.{0,'.$length.'}\\b).*$/s';
        $strText = preg_replace($pattern, "$1...", $strText);
    }
    return $strText;
}
Now I would like to extend my function. Not only should there be a maximum limit of characters (350), but also a limit of number of line breaks (Linux/Windows line breaks), e.g. 10 line breaks.

How to? Eventually directly with a PHP function?


Thanks,
visionmaster