You can count the number of words in a given srting using PHP string function
str_word_count(). See the below code:
Using this PHP string function, you can print number of words in a sentence in a php program. See the below code which prints the number of words in a string:
We are using a PHP variable
$str to hold the input string, number of words of which we want to count. In the next line,
str_word_count($str) is counting the number of words. Then, we are displaying the count. Let us name this file as
index.php and save it in a folder "word_count" under htdocs.
Test the Application
Make sure in your XAMPP control panel Apache and MySQL services are running. Open the browser and run localhost/word_count. You will see the page opened with count displayed in blue color.
Now, let us change the above code little bit. See below:
This time while calling function
str_word_count(), we used a format "1". Default is "0" which counts the number of words. But, if we specify the format as "1", it returns an array with all the words in the sentence. So using a for loop we are displaying the words from the array. Now, if you save it as
word_count.php and run it in browser, it will display the input string itself and the count of words in the string. See below output:
You can also use format as "2" in the function. In that case it will return an associative array. Just use the index and corresponding word as value to display from associative array.
This is an example of using string function in PHP. There are many useful string functions available in PHP, you can use them during PHP programming.