Possible Duplicate:
Extract a fixed number of chars from an array, just full words
I need to truncate strings when they are longer than 20 chars. Words must always stay together, so that this:
say hello to my little friend.
becomes this:
say hello to my...
instead of this:
say hello to my litt...
I set up this function based on a comment in a very old thread. The problem with this regex is that it removes the last word of the sentence (when there are 2 words or more).
function gen_string($string,$min=20) {
$new = preg_replace('/\s+?(\S+)?$/','',substr($string,0,$min));
if(strlen($new) < strlen($string)) $new .= '…';
return $new;
}
Can someone give me a hand with the regex? Thanks!
Solution by Alasdair (with a few retouches)
function gen_string($string,$max=20) {
$tok = strtok($string,' ');
$sub = '';
while($tok !== false && mb_strlen($sub) < $max) {
if(strlen($sub) + mb_strlen($tok) <= $max) {
$sub .= $tok.' ';
} else {
break;
}
$tok = strtok(' ');
}
$sub = trim($sub);
if(mb_strlen($sub) < mb_strlen($string)) $sub .= '…';
return $sub;
}