Word Count

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I was really shocked not to find this already submitted by someone in  
the PHP manual notes.

function jnWordCount($text) {
     $results = array();
     $pattern = '/[\w0-9]+\S+/'; // matches wordy characters and numbers
     return count($results[0]);

$sentence = ' Should be - (ready) ( 53 ) . , =-';
echo jnWordCount($sentence); // outputs 4
// matches: array('Should','be','ready)','53')

It counts the number of words ignoring non-wordy charcters and extra  
whitespace. Infintately better than:

echo count(explode(' ',$sentence));

Which really only counts the number of spaces not the number of words at  
all. The reason I'm posting this here is there is just one slight  
problem. I'm pretty new to regular expressions and they never seem to do  
exactly what I want.

It doesn't seem to want to match single character words.

echo jnWordCount('a 41 I 5'); // outputs 1. A match for '41' only


Re: Word Count

Did you check str_word_count function ???


Re: Word Count

Quoted text here. Click to load it

OMG why does this not appear in the results to a search on "word count"?!

Re: Word Count

Saunders contained the following:

Quoted text here. Click to load it

Stop digging...it does. <g>

Geoff Berrow (put thecat out to email)
It's only Usenet, no one dies.
My opinions, not the committee's, mine.
Simple RFDs http://www.ckdog.co.uk/rfdmaker/

Site Timeline