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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.