PHP Functions - The Str_WordCount Function
When it comes to working with string data, it is often more convenient to use an array than a single string. This is because using an array allows you to take advantage of more advanced features that aren't available when working with a single string. Thankfully, PHP has several in-built functions that can help you convert your string data into an array. This article will discuss one of these, str_word_count.
The str_word_count() function is an in-built function that can be used to return information about the words used in a string and their positions in the string. This function takes an input string as a parameter and returns the result based on the format value you specify.
Format 0 (default): The function returns the total number of words present in the string. Format 1: The function returns an associative array with the words as values and their numeric position within the string as keys. Format 2: The function returns an associative array in which the key is the numeric position of the word and the value is the actual word.
The str_word_count() function uses the preg_split() function to split the initial string into smaller sub-strings of equal length, and then storing these in an array. This function also has an optional chars parameter that can be used to define additional characters that should be considered as words, in addition to the ones defined in the standard character set. The first example above shows how this works, by separating the string "m0re" into two separate words - the front part'm' and the back part're'.