ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.


Word Count

This function allows you to quickly calculate how many words a string contains. Very useful for word processor scripts!

function wordcount($str) { 
count(explode(" ",$str));

// Example Usage:
$test "This has four words.";
"There are " wordcount($test) . " in that sentence";

One Response to “Word Count”

  1. Jian Wu Says:

    Make sure you also use array_filter function to filter out false elements when your string has double, triple or multiple spaces between words. So the function should become this:

    function wordcount($str) {
    return count(array_filter(explode(’ ‘, $str)));

Leave a Reply