Write a PHP program to count the total number of words in a given string

Counting the total number of words in a string is a common programming task in PHP. It is useful when developing applications such as word counters, text analyzers, content management systems, and writing tools.

PHP Program: Count Total Number of Words in a String
Program:

<?php

$str = "PHP is a powerful programming language";

$totalWords = str_word_count($str);

echo "Total Number of Words: " . $totalWords;

?>

Output:

Total Number of Words: 6

Explanation

PHP provides a built-in function called str_word_count() that makes it easy to calculate the total number of words in a given string. This function accepts a string as its argument and returns the number of words found in that string.

In the above program, we first declare a variable named $str and assign it a sentence containing several words. Next, we use the str_word_count() function to count the total number of words and store the result in the $totalWords variable.

Finally, we use the echo statement to display the result on the screen.

For example, the string "PHP is a powerful programming language" contains six words. Therefore, the program displays "Total Number of Words: 6".

This function is simple, fast, and easy to understand. It is supported in PHP 7.4 and PHP 8.x versions. However, its default word-counting rules are primarily designed for English-style text and may need additional handling for other languages.

12 Views