By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,312 Members | 1,850 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,312 IT Pros & Developers. It's quick & easy.

Word Count

P: n/a
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
preg_match_all($pattern,trim($text),$results);
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
?>

Ideas?
Nov 22 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Did you check str_word_count function ???

bye...

Nov 22 '05 #2

P: n/a
> Did you check str_word_count function ???

bye...

OMG why does this not appear in the results to a search on "word count"?!
Nov 22 '05 #3

P: n/a
Message-ID: <FK******************************@pipex.net> from Oliver
Saunders contained the following:
Did you check str_word_count function ???

bye...

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


Stop digging...it does. <g>

http://uk2.php.net/manual-lookup.php...+count&lang=en
--
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/
Nov 22 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.