PHP str_word_count() Function – Description, Parameters, Return Values, and Usage Examples
This article explains PHP's str_word_count() function, detailing how it counts words in a string, the optional format and charlist parameters, the possible return types (integer or array), and provides multiple code examples demonstrating different usage scenarios.
Function Overview The str_word_count() function returns information about the words used in a given string. By default it returns the number of words as an integer, but with the optional format parameter it can return an array of words, an associative array of word positions, or both.
Parameters string – The input string to be analyzed. format – Determines the type of return value. Supported values are:
0 – Return only the word count (integer).
1 – Return an indexed array containing all words.
2 – Return an associative array where keys are the numeric positions of the words in the string and values are the words themselves. charlist – (Optional) A string of additional characters to be considered part of a word.
Return Value Depending on the format argument, the function returns either an integer (word count) or an array (list of words or word positions).
Example Code
<?php
$str = "Hello fri3nd, you're
looking good today!";
print_r(str_word_count($str, 1)); // returns an indexed array of words
print_r(str_word_count($str, 2)); // returns an associative array with positions
print_r(str_word_count($str, 1, "àá??3")); // includes additional characters as part of words
echo str_word_count($str);
?>Sample Output
Array
(
[0] => Hello
[1] => fri3nd
[2] => you're
[3] => looking
[4] => good
[5] => today
)
Array
(
[0] => Hello
[6] => fri3nd
[10] => you're
[29] => looking
[46] => good
[51] => today
)
7The examples illustrate how different format values affect the output, and how the optional charlist can be used to treat additional characters as part of words.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
