// Does the text need to be shortened?
if (strlen($text) <= $maxLength) {
return $text;
}
$appendString = '...';
// plus 1, because of prepended space to $appendString
$maxLength = $maxLength - (strlen($appendString)+1);
preg_match("/(.{0,$maxLength}\b)/s", $text, $textShort);
$shortenedText = (isset($textShort[0]) ? $textShort[0] : '')
. ' ' . $appendString;
// if the text has not enough words to reach minLenght,
// shorten hard.
if (!isset($textShort[0]) ||
($minLength !== null &&
strlen($textShort[0]) < $minLength)) {
// minus 1, because of no prepended space to $appendString
$shortenedText = substr($text, 0, $minLength-1)
. $appendString;
