limit amount of text returned from database field

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tom8521
Forum Commoner
Posts: 25
Joined: Thu May 13, 2010 6:24 am

limit amount of text returned from database field

Post 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.
wanger220
Forum Newbie
Posts: 19
Joined: Tue Feb 02, 2010 8:44 pm

Re: limit amount of text returned from database field

Post 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.
wanger220
Forum Newbie
Posts: 19
Joined: Tue Feb 02, 2010 8:44 pm

Re: limit amount of text returned from database field

Post 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.
mikosiko
Forum Regular
Posts: 757
Joined: Wed Jan 13, 2010 7:22 pm

Re: limit amount of text returned from database field

Post 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
Post Reply