CSC 325 Grinnell College Fall, 2008
 
Databases and Web Application Design
 

Laboratory Exercise on Strings in PHP

This laboratory exercise provides practice with strings and string functions in PHP.

The textarea Element for HTML Forms

In the earlier lab on dynamic Web pages, we worked with forms and input boxes as a mechanism for getting data into a PHP program. Another type of input is the textarea box. For example, the code


    <textarea name="example" cols=50 rows = 12></textarea>

specifies a box that is 50 columns wide and 12 rows tall:

After clicking submit, we can retrieve data entered into this box with the $_GET and $_POST variables, just as for other types of input data.

Strings and String Functions

Chapter 4 of our textbook describes a variety of string functions available within PHP. You may also want to consult the PHP Manual. (Look under "Text Processing" in the "Function Reference Chapter". With this section, consult the "String Functions" link under "Strings".)

Consider the following problem:

Counting Words:

Retrieve text from a textarea box, and count the number of times each word appears.

Possible Algorithm

One possible algorithm for solving this problem is:

  1. Retrieve the text (e.g., from the $_GET and $_POST associative arrays)
  2. Remove punctuation and digits (e.g., use PHP function ctype_alpha to identify a character as being alphabetic; use functions str_replace or substr_replace to replace any non letter by spaces)
  3. Collapse successive spaces by a single space (e.g., also using str_replace or substr_replace — perhaps repeatedly)
  4. Reduce all letters to lower case (e.g., using PHP function strtolower)
  5. Explode the string into an array of word (e.g., using PHP function explode
  6. Sort the array of words
  7. Process successive words,

Steps for this Lab

  1. Step F in the outline specifies that the list of words be sorted. For both approach 1 and approach 2 in Step G, explain any significance of Step F. For example, will the approach work without sorting? Will the sorting be useful, even if it is not essential? How would the result be different if sorting was not done?

  2. Implement both algorithms (i.e., using both approaches 1 and 2 in Step G) in PHP code.

Work to Turn In


This document is available on the World Wide Web as

     http://www.walker.cs.grinnell.edu/courses/325.fa08/lab-php-strings.shtml

created 20 August 2008
last revised 17 September 2008
Valid HTML 4.01! Valid CSS!
For more information, please contact Henry M. Walker at walker@cs.grinnell.edu.