| PHP Count Words from a string |
|
|
|
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) 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. 2. It counts also the punctuation signs Considering these mistakes we will come up with a new function that will solve these problems. function adv_count_words($str){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). 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
|

Count Words from a String 
