How 2 Count number words in a string.

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
jclarkkent2003
Forum Contributor
Posts: 123
Joined: Sat Dec 04, 2004 9:14 pm

How 2 Count number words in a string.

Post by jclarkkent2003 »

Hi,
how to count # words in a string?

Code: Select all

$num_words_string = sizeof(explode(" ",$string));
only way? or is there an eaiser better way?
Ree
Forum Regular
Posts: 592
Joined: Fri Jun 10, 2005 1:43 am
Location: LT

Post by Ree »

It's ok if you're sure each word is separated by a single space. However, count() is more widely used, I think (functionality is the same as sizeof()).
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

count() = sizeof(), sizeof() = count() (they're aliased)

ahem: str_word_count()
jclarkkent2003
Forum Contributor
Posts: 123
Joined: Sat Dec 04, 2004 9:14 pm

Post by jclarkkent2003 »

HAH, how did i not see that one in php.net.... That's where I am 90% of the day, lol...
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Post by josh »

Also as a general idea of how to find optimizations to things like this ( I know the function exists that does this for you but this applies to programming in general not just this function )

Look at what your code does, it splits on the space and then counts the elements, what this is basically doing is counting the number of spaces inside the string, so to optimize you would just count the number of spaces (instead of creating an array, then having the count function, etc.. which brings more overhead into the application)
Post Reply