String functions for first 10 words

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
dimxasnewfrozen
Forum Commoner
Posts: 84
Joined: Fri Oct 30, 2009 1:21 pm

String functions for first 10 words

Post by dimxasnewfrozen »

I have a large database value as a string.

Is there a string function to display the first 10 words of the string as like a description?
Reviresco
Forum Contributor
Posts: 172
Joined: Tue Feb 19, 2008 4:18 pm
Location: Milwaukee

Re: String functions for first 10 words

Post by Reviresco »

Code: Select all

$words = explode(' ', $string);
for($i=0; $i<10; $i++) {
    echo $words[$i] . ' ';
    }
or

Code: Select all

$words = explode(' ', $string);
$description = '';
for($i=0; $i<10; $i++) {
    $description .= $words[$i] . ' ';
    }
dimxasnewfrozen
Forum Commoner
Posts: 84
Joined: Fri Oct 30, 2009 1:21 pm

Re: String functions for first 10 words

Post by dimxasnewfrozen »

Oh awesome, I actually found this example:

Nice to know there's multiple ways to do this

Code: Select all

 
function wordlimit($string, $length = 5, $ellipsis = "...")
    {
           // Only display a description of the content in the news box.
           $words = explode(' ', $string);
           if (count($words) > $length)
               return implode(' ', array_slice($words, 0, $length)) . $ellipsis;
           else
               return $string;
    }  
 
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: String functions for first 10 words

Post by pickle »

wordwrap() might also be useful.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply