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).
It’s often useful to determine the total number of characters or words in a given string. Although PHP’s considerable capabilities in string parsing has long made this task trivial, two functions were recently added that formalize the process. Both functions are introduced in this section.
Counting the Number of Characters in a String
The functioncount_chars()offers information regarding the characters found in a string. Its proto- type follows:
mixed count_chars(string str [, mode])
Its behavior depends on how the optional parametermodeis defined:
0: Returns an array consisting of each found byte value as the key and the corresponding frequency as the value, even if the frequency is zero. This is the default.
1: Same as0, but returns only those byte values with a frequency greater than zero.
2: Same as0, but returns only those byte values with a frequency of zero.
3: Returns a string containing all located byte values.
4: Returns a string containing all unused byte values.
The following example counts the frequency of each character in$sentence:
<?php $sentence = "The rain in Spain falls mainly on the plain";
// Retrieve located characters and their corresponding frequency. $chart = count_chars($sentence, 1);
-------------------------------------------- Character appears 8 times Character S appears 1 times Character T appears 1 times Character a appears 5 times Character e appears 2 times Character f appears 1 times Character h appears 2 times Character i appears 5 times Character l appears 4 times Character m appears 1 times Character n appears 6 times Character o appears 1 times Character p appears 2 times Character r appears 1 times Character s appears 1 times Character t appears 1 times Character y appears 1 times --------------------------------------------