Robson » Little Red Book » Letter frequency

Chapter 7 - Question 13

Process some input text to produce a frequency count for each letter of the alphabet.

Solution 1

<?
   // if there is no user input text
   // or the input text is really long
   if (!$_POST['input_text'] || strlen($_POST['input_text']) > 1000)
       // just make some up
       $_POST['input_text'] = "Perfection isn't achieved when nothing can be added, but when nothing can be taken away.";
   
   // save the original text
   // remove xhtml tags and slashes
   $_POST['input_text'] = strip_tags(stripslashes($_POST['input_text']));
   
   echo '&quot;' . htmlspecialchars($_POST['input_text']) . '&quot;<br /> <br />Has the following letters:<br />';
       
   // loop through all the letters in the alphabet
   for ($n = ord('a'); $n <= ord('z'); $n++)
       // count the number of times that letter appears in the input text
       // and add it to the array
       $letter[chr($n)] = substr_count(strtolower($_POST['input_text']), chr($n));
       
   // sort the array by the values in reverse order (highest to lowest)
   arsort($letter);
   
   // output aligned for easier reading
   echo '<pre>';
   // now loop through all the letters in the array
   for ($n = 0; $n < count($letter); $n++)
   {
       // grab the key and the value from the letter array
       list($key, $val) = each($letter);
       // if that letter was contained somewhere in the string
       if ($val)
           // show the letter frequency
           echo $key . ' - ' .  $val . '<br />';
   }
   // return to normal font
   echo '</pre>';
?>

Which produces:

"Perfection isn't achieved when nothing can be added, but when nothing can be taken away."

Has the following letters:
n - 11
e - 10
a - 7
t - 6
i - 5
h - 5
d - 4
c - 4
o - 3
b - 3
w - 3
g - 2
s - 1
r - 1
v - 1
u - 1
k - 1
f - 1
y - 1
p - 1
Test your text



Log

© 2004-17 robson | cc unless stated