Counting the Total Number of Words in a String - PHP
In this conclusion to a five-part series on strings and regular expressions in PHP, you'll learn about padding and stripping a string, trimming characters from a string, counting the characters in a string, and more. This article is excerpted from chapter nine of the book Beginning PHP and Oracle: From Novice to Professional, written by W. Jason Gilmore and Bob Bryla (Apress; ISBN: 1590597702).
The functionstr_word_count()offers information regarding the total number of words found in a string. Its prototype follows:
mixed str_word_count(string str [, int format])
If the optional parameterformatis not defined, it will simply return the total number of words. Ifformatis defined, it modifies the function’s behavior based on its value:
1: Returns an array consisting of all words located instr.
2: Returns an associative array, where the key is the numerical position of the word instr, and the value is the word itself.
Consider an example:
<?php $summary = <<< summary In the latest installment of the ongoing Developer.com PHP series, I discuss the many improvements and additions to PHP 5's object-oriented architecture. summary; $words = str_word_count($summary); printf("Total words in summary: %s", $words); ?>
This returns the following:
-------------------------------------------- Total words in summary: 23 --------------------------------------------
You can use this function in conjunction witharray_count_values()to determine the frequency in which each word appears within the string:
<?php $summary = <<< summary In the latest installment of the ongoing Developer.com PHP series, I discuss the many improvements and additions to PHP 5's object-oriented architecture. summary; $words = str_word_count($summary,2); $frequency = array_count_values($words); print_r($frequency); ?>