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
Syntax
str_word_count(string $string, int $format = 0, ?string $characters = null): array|int
Parameters
| Parameter | Description |
|---|---|
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
<?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
)<?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))andcount()the result.
Version history
| Version | Change |
|---|---|
| PHP 4.3 | Added |
Related
explode()· Split a string into an array by a separator, like turning "a,b,c" into ["a", "b", "c"]. A limit caps the pieces.strlen()· Return the length of a string in bytes. Multibyte characters such as é count as several bytes; use mb_strlen() to count characters.- PHP Strings · tutorial