Advanced Count Word with PHP
By Administrator • Jan 22nd, 2009 • Category: Web ProgrammingConsidering 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
Administrator is
Email this author | All posts by Administrator


