In the previous article "PHP String Learning: Converting the Size of the First Character (3 Methods)", we learned about converting the first character of each word in the string to uppercase Methods. This time we continue to look at the words in the PHP string and talk about the method of calculating the number of words in the string. Friends who are interested can learn~
How do we know how many words are contained in a string? ? How to count the number of words in a string? Let’s take a look at it today.
Method 1: With the help of array
we can split the string and convert each word in the string into an array element in the array; then Just count the number of array elements.
For example, I have a string like this. The number of words in the string is 9:
$str = "the quick brown fox jumps over the lazy dog";
You can first use the explode() function to split the string into several parts based on spaces. substrings, then combine these substrings into an array and return it.
$arr = explode(' ', $str);
Use var_dump($arr)
Output to see the result:
It can be seen that an element in the array corresponds to the string A word; therefore we can use count() to count the number of array elements, and then we will get the number of words in the string. The implementation code is given below:
The output result is:
##2. Use str_word_count() function
In fact, PHP has a built-in function str_word_count() to count the number of words in a string.str_word_count($str) in the above code example will Can return the number of words. Let’s take a look at the str_word_count() function:
str_word_count($string,$return,$char)The function accepts 1 required parameter
$string, 2 optional Omitted parameters
$return and
$char.
$char is used to specify the special characters that are recognized as words, which will not be introduced here; let’s talk about them in detail. Omitted parameters
$return.
$return is used to specify the return value of the str_word_count() function. There are three values:
0 - The default value, will return the number of words found (that is, the result above).
1 - returns an array containing the words in the string.
2 - Return An array where the keys are the word positions in the string and the keys are the actual words.
Okay, that’s it for now. If you want to know anything else, you can click here. → → Finally, I recommend reading a classic course "
PHP String Processing (Jade Girl Heart Sutra Edition)", it's free~ come and learn !
The above is the detailed content of PHP string learning: How to know how many words are contained in a string. For more information, please follow other related articles on the PHP Chinese website!