Write a PHP program to count the words in the string

Description: Write a PHP program to count the number of words in a string.

Rules and hints:

  • Use only one variable.
  • Use a PHP built-in string function.

PHP program to count the words in a string

<?php
$sample_words = "This is Tutorials Class, learn programming tutorials here.";

echo str_word_count($sample_words);
?>

Output:

Tutorials Class - Output Window

8

How it works

  • str_word_count() counts the words made of letters. Commas and spaces are not counted as words.
  • The sentence has 8 words.

More about it: How to count the words of a string in PHP.


Learn more about the similar topics:
Tutorials
PHP String Handling
Exercises & Assignments
Write a PHP program to reverse the string
Write a PHP program to find the length of the string
Write a PHP program to count the words in the string
Write a PHP program to convert a string into uppercase
PHP Array to String Conversion (favourite colours chosen by user)
Interview Questions & Answers
No Content Found.