One person has asked me to write a function in PHP to count number of words in a string.
You don’t have to use any inbuilt function in PHP except strlen and strpos.
Imagine if you have to do this problem using inbuilt PHP function. Then you can do
it easily through str_word_count(). You need to just pass the string and you get the word count.
In my previous post, i explained the logic to count number of words.
Logic of a Problem
To solve this problem, traverse the string character by character. If you don’t find space increment wordcount by 1, then reach at the end of a word to avoid multiple count of the same word.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$str=" This is a string count program "; $wordcount = 0; for($i=0;$i < strlen($str);$i++){ if($str[$i]!=' '){ $wordcount++; while($str[$i]!=' '){ $i++; } } } echo "Total word count is".' '. $wordcount; |
Most Used Array Function in PHP
Function in PHP to Count Words in a String
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function word_count($str) { $wordcount = 0; for($i=0;$i < strlen($str);$i++){ if($str[$i]!=' '){ $wordcount++; while($str[$i]!=' '){ $i++; } } } return $wordcount; } |
If you have any other good method. You can suggest us in comment.