Robson » Little Red Book » Text processing #2

Chapter 6 - Question 12

Process input text from the keyboard to count the number of words and sentences entered.

Solution 1

   // some text to process later
   // this is the start of the Apache readme file
   $text = "The Apache HTTP Server is a powerful and flexible HTTP/1.1 compliant
web server.  Originally designed as a replacement for the NCSA HTTP
Server, it has grown to be the most popular web server on the
Internet.  As a project of the Apache Software Foundation, the
developers aim to collaboratively develop and maintain a robust,
commercial-grade, standards-based server with freely available
source code.";
   // something like Mr. Smith would count as a sentence start/end
   // so replace anything like that with something else
   // this isn't a comprehensive list, it's just to give an idea
   $text = str_replace(array('Mr.', 'Mrs.', 'Dr.'), 'xx', $text);
   // count the number of sentences
   $sentences = substr_count($text, '. ')+1;
   // remove additional spaces
   $text = str_replace(array(chr(13), chr(10)), ' ', $text);
   $text = eregi_replace(' +', ' ', $text);
   // count the number of words
   $words = substr_count($text, ' ')+1;
   // show the number of lines and characters
   echo 'Sentences: ' . $sentences . '<br/>Words: ' . $words;

Which produces:

Sentences: 3
Words: 62

Microsoft Word says there are 62 words contained in this paragraph.


© 2004-19 robson | cc unless stated