Navigation:    Home arrow Count Words from a String
PHP Count Words from a string PDF  
Digg Reddit Ma.gnolia Stumble Upon Facebook Twitter Google Yahoo! MyWeb Furl" BlinkList Technorati Mixx Bookmark
Learn how to count the words from a string using php.

Considering words are separated by spaces only into a text string, the next function might seem perfect for the purpose:

function count_words($str) 
$no = count(explode(" ",$str));
return $no;

This function breaks the string into pieces separated by spaces and counts them.

But things are not so easy as they seem. Looking for particular cases, we might find the following cases:

1. The user enters two or more spaces instead of one.
Ex. Using the given function for the following sentence: "This is      the     first sentence" will return 14 words instead of 5, because it is counting spaces too as words.

2. It counts also the punctuation signs
Ex: For "This is the second one , it will count wrong as well" , it will count 12 instead of 11 because the comma is counted too.

Considering these mistakes we will come up with a new function that will solve these problems.

 function adv_count_words($str){
$words = 0;
$str = eregi_replace(" +", " ", $str);
$array = explode(" ", $str);
for($i=0;$i < count($array);$i++)
if (eregi("[0-9A-Za-zÀ-ÖØ-öø-ÿ]", $array[$i]))
return $words;
The code explained:
We replace all consecutive space characters with a single space character, for the script not to count spaces too:


$str = eregi_replace(" +", " ", $str); 

Break the string into pieces that are separated by spaces and place them into an array:

$array = explode(" ", $str);

For every string in the array, we make one more test to assure it is a word. We assume that are words only strings that contain at least a letter character (we will not count commas for example).
The line:

if (eregi("[0-9A-Za-zÀ-ÖØ-öø-ÿ]", $array[$i]))

checks for existence of letter characters, including the special characters and increments the number of words if found.

If you found this tutorial useful you might be interested to read the following:

Installing Apache, PHP, MySQL on a Windows 98/2000/XP Computer
PHP Form image verification
PHP Create Image Thumbnail
PHP Form Image Upload
PHP print random image from a folder