Word Count

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Oliver Saunders

    Word Count

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

    <?
    function jnWordCount($te xt) {
    $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($se ntence); // 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?
  • hakim

    #2
    Re: Word Count

    Did you check str_word_count function ???

    bye...

    Comment

    • Oliver Saunders

      #3
      Re: Word Count

      > Did you check str_word_count function ???[color=blue]
      >
      > bye...[/color]


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

      Comment

      • Geoff Berrow

        #4
        Re: Word Count

        Message-ID: <FK-dnVMfPfmN3ebenZ 2dnUVZ8qmdnZ2d@ pipex.net> from Oliver
        Saunders contained the following:
        [color=blue][color=green]
        >> Did you check str_word_count function ???
        >>
        >> bye...[/color]
        >
        >
        >OMG why does this not appear in the results to a search on "word count"?![/color]

        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/

        Comment

        Working...