This document provides instructions for Lab 4 of an information systems design course. The lab aims to build experience with fundamental PHP functions related to arrays, strings, and regular expressions. Students will modify PHP code snippets to work with multi-dimensional arrays, define and call functions, and perform string operations like searching and replacing text. The lab consists of 4 steps involving PHP code to demonstrate various PHP features and concepts.
1. IELM 511 Information Systems Design
Lab 4: Fundamental PHP functions: II
This lab will use a few more exercises to build up your experience with PHP scripts. In
subsequent labs, you will write CGI programs that connect to a Database and exchange
information with the DB, returning the feedback to the web client. Since most data in DBs
is stored in tables, and cell entries are mostly strings, therefore the two data types we need
to handle in our programs are (multi-dimensional) arrays, and strings. In this lab, we will
build up some more experience with these, working on basic language skills for PHP.
Objectives of this lab
Gain some familiarity with the following concepts:
(a) Basic data structures in PHP: multi-dimension arrays
(b) Program flow control: functions
(c) Regular expressions and string parsing.
As before, if you need to look up the syntax of some operator/function in PHP, you can use
a good online PHP tutorial site, such as: http://www.w3schools.com/PHP/
The lab tasks are below.
Step 1. [Re-use from past lab]. Make a simple web-form (file: run_cgi.html) with one
input field and one text-box field (use or modify the file given to you in the lab materials).
Step 2. Try the following code using phpDesigner, and then modify it as instructed.
In most php program, we work with strings; common examples:
- If you read a line of data from a file, you will read it as a string of characters;
- The most common data types stored in a Database are strings.
PHP provides several useful string functions and operators.
<?php
$x = "I love"; // declare a variable, $x, and define its value(of type string)
$y = " PHP !"; // declare and define variable $y
$z = $x . $y; // the dot-operator, ‘.’ is used to join two or more strings.
echo $z; // This should print: I love PHP !
echo "<br>";
$z = $z . " Yes, " . $z . " Oh yes, " . $z;
echo( $z); // This example shows how to join many strings using ‘.’
echo "<br>";
$z = str_replace( "love", "hate", $z); // replace a part of a string with another
echo $z, "<br>";
2. if ( substr_count( $z, "hate") >= 2) {
/* substr_count( ) counts no of times a sub-string
occurs in a given string */
echo "Oh no, why do you hate me so much ?", "<br>";
}
?>
What you learnt:
1. Useful string functions: str_replace, substr_count.
Exercise: Modify the code above as follows: $x should store the abstract of a paper written
by your advisor (or your favorite professor). $y should be an array of keywords of the
paper. Your program should output how many times each keyword occurs in the abstract.
Step 3. User-defined functions and multi-dimensional arrays
In this example, you will learn:
(i) How to define your own functions
(ii) Note how to return values from your functions: these can be variables, arrays, etc.
(iii) Learn how to define named constants (same as #define in C++)
(iv) Learn some math functions in PHP
(v) Learn how to use “printf” function for formatted output.
<?php
// We define a function to multiply a 1x2 vector with a 2x2 matrix
function vect_mult_mat( $vec, $mat) {
$out[0] = $vec[0] * $mat[0][0] + $vec[1] * $mat[1][0];
$out[1] = $vec[0] * $mat[0][1] + $vec[1] * $mat[1][1];
return $out;
}
// The define function is similar to #define in C++
// PHP has all common math functions, e.g. sin, cos, …
define ("PI", 3.1415926);
$cos_theta = cos( PI/4.0);
$sin_theta = sin( PI/4.0);
// item-by-item definition of a multi-dimensional array
$rot_matrix[0][0] = $cos_theta; $rot_matrix[0][1] = $sin_theta;
$rot_matrix[1][0] = -1.0 * $sin_theta; $rot_matrix[1][1] = $cos_theta;
$my_vector = array( 2.0, 2.0);
// We call the function defined earlier; notice that it returns an array!
$rotated_vector = vect_mult_mat( $my_vector, $rot_matrix);
echo "Vector [ $my_vector[0], $my_vector[1] ], when rotated by PI/4, goes to
[ $rotated_vector[0], $rotated_vector[1] ] <br>n";
3. // Notice how echo prints floating point numbers -- quite ugly!
// For formatted output, it is better to use the printf function of PHP
printf( "Vector [ $my_vector[0], $my_vector[1] ], when rotated by PI/4, goes to [ %4.2f,
%4.2f ] <br>n", $rotated_vector[0], $rotated_vector[1] );
?>
What you learnt:
1. One way to define a multi-dimensional array. Such arrays will be very useful when you
need to handle data coming from a DB – since each DB table is similar to a 2D array.
2. One way to define and use your own functions in PHP; notice that our function worked
by passing the value of its arguments; PHP also allows you to pass references to arguments,
which is sometimes useful.
3. A simple use of the printf function; this function is quite useful in generating pretty
output.
Exercise: Modify the code above as follows. First create a multi-dimensional array called
$loans, with the data from the table below (no need to store the attribute names). Write a
function which takes a 2-dimensional array as input, and outputs an HTML table that looks
like the table below (namely, it prints the top row with the given attribute names, and then
the rows of the array). Your main PHP program should output sub-arrays from the input
array such that each sub-array has only the data for a particular loan (e.g. there will be an
array of three rows for L17). Call the print_table function once for each sub-array and
display the output via the web client.
customer loan_no amount branch_name
111-12-0000 L17 1000 Downtown
222-12-0000 L23 2000 Redwood
333-12-0000 L15 1500 Pennyridge
444-00-0000 L93 500 Mianus
666-12-0000 L17 1000 Downtown
111-12-0000 L11 900 Round Hill
999-12-0000 L17 1000 Downtown
777-12-0000 L16 1300 Pennyridge
Step 4. Working with strings: Regular expressions.
When working with web-based applications and DB, you will often be processing data in the
form of strings of characters.
Regular expressions (RegExps) are a very powerful method to do pattern matching on
strings. Many string functions use RegExps.
4. <?php
// Define a string
$text = "Never let a fool kiss you, never let a kiss fool you";
echo "Text is: $text <br>n";
// Two ways to search for a constant string in a long string:
// strstr( ), and preg_match( )
// Notice how the ‘’ is used to escape the "-mark in the argument of echo.
if ( strstr( $text, "fool") ) { echo "strstr: Found "fool" in text <br>n";}
if ( preg_match( "/fool/", $text) ) { echo "preg_match: Found "fool" in text <br>n";}
// preg_match_all( ) can be used for case-insensitive search,
// and multiple matches
// In the RegExp, the pattern to match is between the /…/
// the ‘i’ at the end indicates that the match should be case-insensitive
$no_of_hits = preg_match_all( "/never/i", $text, $matches);
echo "preg_match_all: Found $no_of_hits instances of "never" in text; they were: ";
for ($i = 0; $i < $no_of_hits; $i++) { echo $matches[0][$i], ", "; }
echo "<br> n";
// to catch all instances of ‘fool’ or ‘kiss’, use the ‘|’ in the RegExp
$no_of_hits = preg_match_all( "/fool|kiss/", $text, $matches);
echo "preg_match_all: Found $no_of_hits instances of "fool" or "kiss" in text; they
were: ";
for ($i = 0; $i < $no_of_hits; $i++) { echo $matches[0][$i], ", "; }
echo "<br> n";
?>
What you learnt:
1. Regular expressions are in fact a very powerful concept; we only saw the simplest
RegExps. You will see many other uses in future labs – you can use RegExps to search for
very complicated and patterns.
Exercise: Write a CGI program that will receive the abstract of a paper submitted by a form
via a web client. Your CGI program should search for the following incorrectly spelt words
in the abstract. It should then return the same text to the web client, except that all the
incorrectly spelt words should be colored in red, and the corrected spelling is suggested in
brackets, in blue color.
List of incorrect spellings to check:
teh the
Teh The
acn can
5. abotu about
actualyl actually
For example, if the input text is:
Teh quick brown fox acn jump over the lazy fox.
Then the output should be:
Teh [do you mean: The] quick brown fox acn [do you mean: can] jump over the lazy fox.
References:
1. HTML quick reference file.
2. PHP tutorials and function references: (from www.php.net)
3. PHP tutorial site: http://www.w3pop.com/learn/view/p/3/o/0/doc/php_ref_string/
4. Another PHP tutorial/reference: http://www.w3schools.com/PHP/php_ref_array.asp
Lab materials for IELM 511 prepared by WEI Xiangzhi, Dept of IELM, HKUST.