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:
4Text 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