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.
limit amount of text returned from database field
Moderator: General Moderators
Re: limit amount of text returned from database field
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.
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
Something along the lines of:
That should work, but of course be sure to clean the text before explode(), otherwise it may not count properly.
Code: Select all
$desc = explode(' ', $description);
$words = count($desc);
if ($words > 250) {
$snippet = array_slice($desc,0,250);
echo $snippet;
} else {
echo $desc }
Re: limit amount of text returned from database field
this could be util for you too, assuming that your word's separator is a space
miko
Code: Select all
SELECT SUBSTRING_INDEX(your_text_field, ' ', 250) from your_table;