Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

str_word_count

Counts the words in a string.

Syntax

str_word_count(string $string, int $format = 0): array|int

Parameters

ParameterTypeDescription
$stringstringThe source string.
$formatintOptional. `0` returns the count, `1` an array of words.

Return value

array|intThe number of words, or an array of words.

Examples

The number of words:

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

Output:

4

The list of words:

<?php
 
echo implode(' | ', str_word_count('Hello, big world!', 1));

Output:

Hello | big | world

Notes

The function understands ASCII letters only. Count words in other languages with count(preg_split('/\s+/u', trim($text))).

See also

  • explode — Splits a string into an array by a separator.
  • substr_count — Counts how many times a substring occurs in a string.

In the tutorial

  • Strings — Working with strings in PHP — quotes, concatenation, length, searching, replacing and multibyte functions.

Thanks for reading!

Donate to the site — we work hard for you.