What is the str_word_count method in PHP?

Overview

In PHP, the str_word_count() method counts the number of words in a string and returns the count value. It has been a part of the standard library in PHP, which has been available since PHP version 4.3 and later.

Illustration of str_word_count() operation

Syntax

 str_word_count($string,$format, $characters)

Parameters

  • $string: The string whose words are counted.
  • $format: This is an integer value that indicates the function’s return value. The supported values are listed below:
    • 0 returns the number of words found.
    • 1 is an array that has all the strings found in $string.
    • 2 returns an associative array. The array key is the numeric position of the word inside the $string, and the array value is the actual word itself.

Note: The $format parameter only supports 0, 1, and 2 as valid values.

  • $character: This parameter indicates the list of other characters to be seen as words.

This function only identifies a group of letters as a word. If a number or any other character is part of the input $string, it is considered a word on its own. In that case, it is only returned as a part of the counted word if passed as a character parameter.

Example

<?php
// a normal string
$str = "It is surely a bright day today";
//string with some space
$strings = "It is surely a bright day today";
// strings with number and special character
$stringing = "Hello wor3ld enjoy y%our day";
// the format param defaults to zero
print_r(str_word_count($str));
echo "\n";
//this will print a simple index array
print_r(str_word_count($str,1));
// an associative array is displayed.
print_r(str_word_count($str,2));
// This count shows that spaces are not counted
echo "\n" ;
print_r(str_word_count($strings));
echo "\n";
/* with the character param the
special char is returned*/
print_r(str_word_count($stringing, 1,'3%'));
echo "\n";
print_r(str_word_count($stringing));
?>

Explanation

  • Line 5–11: We define three string variables $str, $string, and $stringing.

  • Line 14: We count the $str string and print the count result.

  • Line 18: We call the str_word_count() function on the string with the $format parameter passed as 1. It returns an indexed array.

  • Line 25–31: We count the words in the $strings and $stringing string variables.

  • Line 21: We call the str_word_count() function on $stringing with the $format parameter set as 1. It returns an indexed array. We set the $character parameter as 3%. This causes the function to consider 3 and % found in the $stringing variable as separate words.

Free Resources