Page 1 of 1

limit amount of text returned from database field

Posted: Mon May 17, 2010 7:55 am
by tom8521
I have a description field stored in my database. When i retrieve this information it can sometimes be very very long. Is there a way this information can be capped at say 250 words until the user clicks for further details?
Thanks.

Re: limit amount of text returned from database field

Posted: Mon May 17, 2010 8:23 am
by wanger220
Use substr():

echo substr($description,0,250);


Edit: Oops, I just noticed you meant 250 words ... substr counts characters. You'll probably need to do this by counting the number of words using explode(), setting up a conditional that checks whether there are more than 250 words, then grabbing the first 250 words from the explode() array.

Re: limit amount of text returned from database field

Posted: Mon May 17, 2010 8:51 am
by wanger220
Something along the lines of:

Code: Select all

$desc = explode(' ', $description);

$words = count($desc);

if ($words > 250) {
 $snippet = array_slice($desc,0,250);
 echo $snippet;
} else {
 echo $desc }
That should work, but of course be sure to clean the text before explode(), otherwise it may not count properly.

Re: limit amount of text returned from database field

Posted: Mon May 17, 2010 9:07 am
by mikosiko
this could be util for you too, assuming that your word's separator is a space

Code: Select all

SELECT SUBSTRING_INDEX(your_text_field, ' ', 250) from your_table;
miko