How to use trim(), substr_count(), and str_replace() method. In PHP

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.

Example:

PHP
<?php
// PHP program to count number
// of word in a string 
  
// Function to count the words
function get_num_of_words($string) {
    $str = trim($string);
      while (substr_count($str, "  ") > 0) {
        $str = str_replace("  ", " ", $str);
    }
      return substr_count($str, " ")+1;
}

$str = "  Geeks  for    Geeks  "; 
 
// Function call 
$len = get_num_of_words($str);

// Printing the result
echo $len; 
?>

Output
3

How to count the number of words in a string in PHP ?

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:

Table of Content

  • Using str_word_count() Method
  • Using trim(), preg_replace(), count() and explode() method. 
  • Using trim(), substr_count(), and str_replace() method. 
  • Using strtok()
  • Using regular expressions (preg_match_all()

Similar Reads

Using str_word_count() Method

The str_word_count() method counts the number of words in a string....

Using trim(), preg_replace(), count() and explode() method.

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....

Using trim(), substr_count(), and str_replace() method.

Step 1: Remove the trailing and leading white spaces using the trim() method....

Using strtok()

You can count the number of words in a string using strtok() in PHP. Tokenize the string using spaces as delimiters, incrementing a counter for each token until no more tokens are left, effectively counting the words....

Using regular expressions (preg_match_all()

Using `preg_match_all()` in PHP with the pattern `/(\w+)/u` efficiently counts words by matching sequences of word characters (`\w+`). It returns the number of matches found in the string, providing a robust solution for word counting tasks....