|
Posted by Phil on 10/29/31 11:19
ChrisJ wrote:
> I want to take a plain text string of arbitrary length and reduce its
> lenth to a set maximum. However I want the split to be at a word
> boundary (whitespace) not half way through a word.
>
> Is there an easy solution?
I'm no programmer, but I wanted something like this too, so here's a
function I hacked together after I read your message. There's probably a
much easier and more elegant way of doing it, though...
function trim_text($text,$length,$addellipsis=TRUE) {
$words = explode(' ',$text);
$newphrase = '';
$finished = FALSE;
while(!$finished) {
$newphrase .= ' '.array_shift($words);
if(strlen($newphrase.' '.$words[0]) > $length) { $finished = TRUE; }
}
if($addellipsis) { $newphrase .= ' ...'; }
return $newphrase;
}
The $addellipsis bit is because I like to do that if I've truncated the
text, which is why I do it by default.
@+
[Back to original message]
|