Forum Moderators: coopster

Message Too Old, No Replies

Fixing my "Shorten" function.

I need a quick fix for my shorten regex.

         

apacheMan

8:29 pm on Oct 14, 2008 (gmt 0)

10+ Year Member



Hey guys,

I use a function to shorten the length of a string to less than 300 characters for output to screen, but do it in a way as to not break words. It works wonderfully, however, it does NOT work if there is a carriage return in the first 300 characters. I have a feeling my regular expression is at fault for not allowing carriage returns, and was hoping someone here with some regex knowledge could guide me to the proper modification I need to make:

My Shorten Function:

# Shortens string to n number of characters, yet does not break words:
function shorten($str, $n, $delim='...')
{
$len = strlen($str);
if ($len > $n) {
preg_match('/(.{' . $n . '}.*?)\b/', $str, $matches);
return rtrim($matches[1]) . $delim;
}
else {
return $str;
}
}

How I call the function:

echo shorten($longString, 300);

Thank you for any help. Much appreciation.

pinterface

10:25 pm on Oct 14, 2008 (gmt 0)

10+ Year Member



From [us2.php.net ]:
s (PCRE_DOTALL)
    If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.