Given a string containing some words and the task is to count number of words in a string str in PHP. In order to do this task, we have the following approaches:
Approach 1: Using str_word_count() Method: The str_word_count() method is used to counts the number of words in a string.
str_word_count(string, return, char)
Step 1: Remove the trailing and leading white spaces using the trim() method and remove the multiple whitespace into a single space using preg_replace() method.
Step 2: Convert the string into an array using the explode() method.
Step 3: Now count() method counts the number of elements in an array.
Step 4: Resultant is the number of words in a string.
Step 1: Remove the trailing and leading white spaces using the trim() method.
Step 2: Convert the multiple white spaces into single space using the substr_count() and str_replace() method.
Step 3: Now counts the number of word in a string using substr_count($str, ” “)+1 and return the result.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.