Robson » Little Red Book » Text processing #1

Chapter 6 - Question 11

Process input text from the keyboard to count the number of characters and lines 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.";
   // count the number of lines
   $lines = substr_count($text, chr(13))+1;
   // remove the new lines
   $text = str_replace(array(chr(13), chr(10)), '', $text);
   // store the number of characters (including spaces)
   $chars_with_spaces = strlen($text);
   // store the number of characters (without spaces)
   $chars_without_spaces = strlen(str_replace(' ', '', $text));
   // show the number of lines and characters
   echo 'Lines: ' . $lines . '<br/>' .
        'Characters (including spaces): ' . $chars_with_spaces . '<br/>' .
        'Characters (excluding spaces): ' . $chars_without_spaces;

Which produces:

Lines: 1
Characters (including spaces): 396
Characters (excluding spaces): 339

Microsoft Word says there are 7 lines, 339 characters (excluding spaces) and 402 characters (including spaces). Microsoft Word seems to be including new lines as characters, so it's character count including spaces is higher.


© 2004-17 robson | cc unless stated