Not signed in (Sign In)

SkillShare - A place to discuss Web Standards and Web Design topics

Categories

Vanilla 1.1.5a is a product of Lussumo. More Information: Documentation, Community Support.

    • CommentAuthorlatinomigs
    • CommentTimeJun 20th 2007
     permalink
    So I'm new to regex and I've been trying to experiment with a word counter pattern in PHP. I use preg_match_all to get the count of spaces with the following pattern: "/[^(\s\s|\s\s\s)][(\B\s\B)]/"

    This seems like a backwards approach, and it doesn't always accurately match the number of words.

    I want the following to be true:

    "This is a statement" = 4 words
    "This is a statement " = 4 words
    " This is a statement" = 4 words
    " This is a statement " = 4 words
    ... etc...

    I feel like there's gotta be a much more logical solution than my approach, and I'm just not seeing.

    Suggestions?
    • CommentAuthorlatinomigs
    • CommentTimeJun 20th 2007
     permalink
    DUH!

    This pattern does it:

    "/\w+/"

    :)
    • CommentAuthordhayes
    • CommentTimeJun 20th 2007
     permalink
    ..or

    $str = 'this is a statement';
    $parts = explode(' ',$str);
    echo count($parts); // = 4
    • CommentAuthorlatinomigs
    • CommentTimeJun 22nd 2007
     permalink
    I don't think that is as precise. The regex method will count the number words accurately regardless of extra spaces. Exploding by spacing could lead to an inaccurate count unless you code for empty subscripts. Ex:

    $sText = "   This    is  a   simple   string  with   extra spaces   ";

    Regex Method:
    $nWordCount = preg_match_all("/\w+/", $sText, $aArray);
    echo $nWordCount; // 8

    Simple Explode:
    $aParts = explode($sText);
    $nWordCount = count($aParts);
    echo $nWordCount; // 28

    Precise Explode:
    $aParts = explode($sText);
    $nWordCount = 0;
    foreach($aParts AS $value) {
       if(strlen($value) > 0) {
          $nWordCount++;
       }
    }
    echo $nWordCount; // 8
    • CommentAuthordhayes
    • CommentTimeJun 22nd 2007
     permalink
    right, sorry.. i didn't read the examples.. it was just a fly by example :)

    sorry 'bout that.
Add your comments
    Username Password
  • Format comments as (Help)