Maybe something like this?
<?php
function shortenText($text, $length=100)
{
$text = rtrim($text);
if(strlen($text) > $length)
{
$lastWord = array_pop(preg_split('/\s/', $text));
$startLength = $length - 3 - strlen($lastWord);
if($startLength < 1)
{
user_error(__FUNCTION__."(): Unable to shorten string.");
return $text;
}
$start = preg_replace('/^(.{1,'.$startLength.'}\b).*$/s', "$1", $text);
$text = $start.'...'.$lastWord;
}
return $text;
}
//////////
// TEST //
//////////
$string = <<<END
This is a test. It is only a test. Testing one, two, three.
This has been a test.
END;
for($len = 20; $len <= strlen($string) + 20; $len+=10)
{
printf(
"<p><strong>Length %d:</strong<br />\n%s</p>\n",
$len,
shortenText($string, $len)
);
}
Output:
Length 20:
This is a ...test.
Length 30:
This is a test. It is ...test.
Length 40:
This is a test. It is only a ...test.
Length 50:
This is a test. It is only a test. Testing...test.
Length 60:
This is a test. It is only a test. Testing one, two...test.
Length 70:
This is a test. It is only a test. Testing one, two, three. ...test.
Length 80:
This is a test. It is only a test. Testing one, two, three. This has ...test.
Length 90:
This is a test. It is only a test. Testing one, two, three. This has been a test.
Length 100:
This is a test. It is only a test. Testing one, two, three. This has been a test.