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.
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.
$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;
Function in PHP to Count Words in a String.
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.