Here is a function that does what you want, and a test function to check it is working as expected.
function excerpt($title, $cutOffLength) {
$charAtPosition = "";
$titleLength = strlen($title);
do {
$cutOffLength++;
$charAtPosition = substr($title, $cutOffLength, 1);
} while ($cutOffLength < $titleLength && $charAtPosition != " ");
return substr($title, 0, $cutOffLength) . '...';
}
function test_excerpt($length) {
echo excerpt("This is a very long sentence that i would like to be shortened", $length);
echo "
";
echo excerpt("The quick brown fox jumps over the lazy dog", $length);
echo "
";
echo excerpt("nospace", $length);
echo "
";
echo excerpt("A short", $length);
echo "
";
}
test_excerpt(5);
test_excerpt(10);
test_excerpt(15);
test_excerpt(20);
test_excerpt(50);
Outputs -
This is...
The quick...
nospace...
A short...
This is a very...
The quick brown...
nospace...
A short...
This is a very long...
The quick brown fox...
nospace...
A short...
This is a very long sentence...
The quick brown fox jumps...
nospace...
A short...
This is a very long sentence that i would like to be...
The quick brown fox jumps over the lazy dog...
nospace...
A short...