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

Use the str_word_count() function. It returns how many words are in a string.

<?php
echo str_word_count("Hello world, welcome to Tutorials Class");
?>

Output:

Tutorials Class - Output Window

6

If you pass 1 as the second parameter, it returns the words in an array instead of the count.

<?php
$words = str_word_count("Learn PHP today", 1);

print_r($words);
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => Learn
[1] => PHP
[2] => today
)

str_word_count() counts only letters, so numbers are not counted as words, and it does not work well for non-English text. For such text, use count(explode(" ", $text)) or preg_split().


Learn more about the similar topics:
Tutorials
PHP String Handling
PHP explode() Function
PHP strpos() Function
PHP implode() Function
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
Interview Questions & Answers
How will you concatenate two strings in PHP?
What is the difference between single quote and double quote string in PHP?
Why we use PHP String functions trim(), ltrim() and rtrim()?
What PHP Function is used to find position of a string?
What is the use of ucwords() PHP String function?
What is the use of str_replace() PHP String function?
How to find String Length in PHP?