A quick tip here for counting the number of words in a string. For example, when you need to determine if a submitted string is too short to be considered in inclusion or further processing.
$str = 'How to get the number of words in a string?';
$num = str_word_count($str, 0); // $num = 10
The PHP function str_word_count() is a weirdo in that the 2nd argument is a digit from 0 – 2. While it’s 0, str_word_count() counts and returns the total number of words in the string $str.
If it’s 1, str_word_count() returns an array of all the words identified inside the string $str.
Else if it’s 2, str_word_count() returns what it would return when it’s set to 1 but with all the keys being the numeric position of the corresponding word.
Related Posts
- PHP: Count the Number of Occurrences of Each Unique Value in an Array
- PHP Array Length Function to Get Length of Arrays
- PHP String Case: Uppercase all Letters or Lowercase all Letters in a String | Uppercase First Letter of a String | Uppercase First Letter of all Words in a String
- jQuery: How to test or check whether an element exists
- PHP: Count Lines of a File and Get the Number of Lines in a Text File
