PHP 8 reference · String Functions

PHP str_word_count() Function

Count the words in a string, or return them as an array. Words are runs of letters plus ' and -; digits split words.

PHP 8 Since 4.3

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

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

Parameters

ParameterDescription
string The input string.
format optional 0 returns the count, 1 an array of words, 2 an array keyed by each word's position. Default: 0
characters optional Extra characters to treat as part of a word.

Return value

The number of words, or an array of words when format is 1 or 2.

Examples

Count and list wordsTry it yourself
<?php
$text = "The quick brown fox jumps";
echo str_word_count($text), "\n";
print_r(str_word_count($text, 1));

Output

5
Array
(
    [0] => The
    [1] => quick
    [2] => brown
    [3] => fox
    [4] => jumps
)
What counts as a wordTry it yourself
<?php
echo str_word_count("Route 66 is 2,448 miles"), "\n"; // numbers aren't words
echo str_word_count("well-known don't"), "\n";

Output

3
2

Common mistakes

  • Letters outside ASCII (é, ü, Cyrillic) split words, because the function isn't Unicode-aware. For UTF-8 text use preg_split('/\s+/u', trim($text)) and count() the result.

Version history

VersionChange
PHP 4.3Added

Was this page helpful?