str_word_count
Counts the words in a string.
Syntax
str_word_count(string $string, int $format = 0): array|intParameters
| Parameter | Type | Description |
|---|---|---|
| $string | string | The source string. |
| $format | int | Optional. `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:
4The list of words:
<?php
echo implode(' | ', str_word_count('Hello, big world!', 1));Output:
Hello | big | worldNotes
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.