Google News
logo
PHP Program to Count the number of words in a string - str_word_count()
In PHP, `str_word_count()` is used to count the number of words in a string. It counts the number of words in a string and returns the count.

Here's an example :
Program :
<?php
$string = "The quick brown fox jumps over the lazy dog";
$word_count = str_word_count($string);
echo "The number of words in the string is: " . $word_count;
?>
Output :
The number of words in the string is: 9
By default, `str_word_count()` counts only the words in the string, and ignores any numbers or special characters. However, you can specify a second argument to change this behavior.

For example, if you want to include numbers as part of words, you can set the second argument to `1`.
Program :
<?php
$string = "The price of the item is $19.99";
$word_count = str_word_count($string, 1);
echo "The number of words in the string is: " . $word_count;
?>
Output :
The number of words in the string is: 8
In this example, the second argument to `str_word_count()` is set to `1`, which tells it to count numbers as part of words. As a result, the word count includes "19.99" as a single word.