Shorten string and line breaks

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
visionmaster
Forum Contributor
Posts: 139
Joined: Wed Jul 14, 2004 4:06 am

Shorten string and line breaks

Post 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
Post Reply