Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to count words in a string

Short answer

There is a built-in function for English text:

<?php
 
echo str_word_count('The quick brown fox');

Output:

4

Text in any language

str_word_count() does not recognise non-ASCII letters. It is more reliable to strip the ends with trim(), split the string on whitespace and count the parts with count():

<?php
 
$text = '  Быстрая   рыжая лиса ';
 
echo count(preg_split('/\s+/u', trim($text)));

Output:

3

Functions used in this recipe

  • count — Returns the number of elements in an array.
  • trim — Removes whitespace and other characters from both ends of a string.

Thanks for reading!

Donate to the site — we work hard for you.