PHP Strings Primer - Generating Statistics
(Page 22 of 37 )
It is common to see statistics dealing with the text you are working on in many word processors. With PHP, we can emulate these types of statistics. Imagine, if you will, a system where users enter in some text into a form, submit it, and we generate statistics about the character usage and number of words used. Using the three functions we introduced in the beginning of this section, this can easily be accomplished.
The following is a simple example of how we can achieve that task. Rather than accepting the text from a form, we have assigned it to a variable for simplification purposes.
<?php $text = 'We hold these Truths to be self-evident,' . Â Â Â Â Â Â Â ' that all Men are created equal';
/* Find the length of the string */
$length = strlen ($text);
/* Find the frequency of each character */
$frequency = count_chars ($text, 1);
/* Now loop through each character and display   its frequency and percentage of total */
foreach($frequency as $key=>$value) { Â Â Â printf ("The character '%s' appeared %d times, or %.2f " . Â Â Â Â Â Â Â Â Â Â Â "percent of the total.<br />\n", Â Â Â Â Â Â Â Â Â Â Â chr ($key), $value, ($value / $length * 100)); }
/* display the amount of words in the text */
echo "<br />\nThere are " . str_word_count($text) . Â Â Â Â " words in this text.<br />\n"; ?> |
In this example, we have used a different mode for 'count_chars()' than in our previous example. With this mode, we are returned an array with the ASCII values of the characters as the key. You will notice that we used the 'chr()' function to turn that ASCII value into its normal character representation.
As noted earlier, the 'str_word_count()' function is only available in PHP version 4.3.0 and newer. Attempting to use this function in earlier versions will result in an undefined function error.
Without a doubt, you will find many other uses for these three functions. In fact, you will definitely see the use of the 'strlen()' function in many different situations.
Next: Substrings (and searching) >>
More Programming Basics Articles
More By Matt Wade