[thelist] PHP show first 10 words of MySQL field
Kelly Hallman
khallman at wrack.org
Thu Aug 28 12:21:35 CDT 2003
On Wed, 27 Aug 2003, Matt King wrote:
> But that only shows the first 180 characters. Wouldn't it look funny if
> you cut off a word at the end of this string?
>
> Here's a more elegant (but more resource taxing) solution:
> $WordLimit = 20;
> $Words = explode(" ",$String,$WordLimit);
> array_pop($Words); // Last element contains remaining text, we don't need it
> foreach ($Words as $Word) { echo $Word . " "; }
How about:
$trunc = 5; // 5 words
$sentence = 'This is a long sentence of more than five words.';
$result = implode(' ',array_slice(preg_split('/\s/',$sentence),0,$trunc));
For an indicator (or link to the full item) if it was truncated add this:
if (strlen($result) < strlen($sentence)) { $result.= '...'; }
So here's a small function combining the two:
function truncate($inp,$wsize,$truncd='...') {
$r = implode(' ',array_slice(preg_split('/\s/',$inp),0,$wsize));
return $r. ((strlen($r) < strlen($inp))?$truncd:''); }
--
Kelly Hallman
http://wrack.org/
More information about the thelist
mailing list