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:
Code: Select all
# 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;
}
}Code: Select all
echo shorten($longString, 300);