SlideShare a Scribd company logo
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>";
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";
// 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.
<?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
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.

More Related Content

PDF
Practice exam php
Yesenia Sánchez Sosa
 
PPTX
PHP Powerpoint -- Teach PHP with this
Ian Macali
 
PPTX
PHP Basics
Henry Osborne
 
PDF
Functions in PHP
Vineet Kumar Saini
 
PDF
Zend Certification Preparation Tutorial
Lorna Mitchell
 
ODP
PHP Web Programming
Muthuselvam RS
 
ODP
Php Learning show
Gnugroup India
 
PDF
Zend Certification PHP 5 Sample Questions
Jagat Kothari
 
Practice exam php
Yesenia Sánchez Sosa
 
PHP Powerpoint -- Teach PHP with this
Ian Macali
 
PHP Basics
Henry Osborne
 
Functions in PHP
Vineet Kumar Saini
 
Zend Certification Preparation Tutorial
Lorna Mitchell
 
PHP Web Programming
Muthuselvam RS
 
Php Learning show
Gnugroup India
 
Zend Certification PHP 5 Sample Questions
Jagat Kothari
 

What's hot (20)

ODP
Introduction to Perl - Day 1
Dave Cross
 
PDF
PHP7. Game Changer.
Haim Michael
 
PDF
Improving Dev Assistant
Dave Cross
 
PPTX
Data types in php
ilakkiya
 
PPT
Class 5 - PHP Strings
Ahmed Swilam
 
PDF
Perl.Hacks.On.Vim
Lin Yo-An
 
ODP
Introduction to Perl - Day 2
Dave Cross
 
PDF
Perl programming language
Elie Obeid
 
ODP
Advanced Perl Techniques
Dave Cross
 
ODP
perl usage at database applications
Joe Jiang
 
PPT
Manipulating strings
Nicole Ryan
 
PPT
PHP
webhostingguy
 
PPT
Download It
webhostingguy
 
PDF
Ruby cheat sheet
Tharcius Silva
 
PPT
Perl Presentation
Sopan Shewale
 
PPTX
Subroutines in perl
sana mateen
 
PPT
Plunging Into Perl While Avoiding the Deep End (mostly)
Roy Zimmer
 
PPT
PHP - DataType,Variable,Constant,Operators,Array,Include and require
TheCreativedev Blog
 
Introduction to Perl - Day 1
Dave Cross
 
PHP7. Game Changer.
Haim Michael
 
Improving Dev Assistant
Dave Cross
 
Data types in php
ilakkiya
 
Class 5 - PHP Strings
Ahmed Swilam
 
Perl.Hacks.On.Vim
Lin Yo-An
 
Introduction to Perl - Day 2
Dave Cross
 
Perl programming language
Elie Obeid
 
Advanced Perl Techniques
Dave Cross
 
perl usage at database applications
Joe Jiang
 
Manipulating strings
Nicole Ryan
 
Download It
webhostingguy
 
Ruby cheat sheet
Tharcius Silva
 
Perl Presentation
Sopan Shewale
 
Subroutines in perl
sana mateen
 
Plunging Into Perl While Avoiding the Deep End (mostly)
Roy Zimmer
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
TheCreativedev Blog
 
Ad

Similar to lab4_php (20)

PDF
PHP tips and tricks
Damien Seguy
 
PDF
Php tips-and-tricks4128
PrinceGuru MS
 
DOCX
PHP record- with all programs and output
KavithaK23
 
PPTX
Php functions
JIGAR MAKHIJA
 
PPT
Php my sql - functions - arrays - tutorial - programmerblog.net
Programmer Blog
 
PPT
Php introduction
Osama Ghandour Geris
 
PPTX
overview of php php basics datatypes arrays
yatakonakiran2
 
PPTX
07-PHP.pptx
ShishirKantSingh1
 
PPTX
07-PHP.pptx
GiyaShefin
 
PPT
Synapse india complain sharing info about php chaptr 26
SynapseindiaComplaints
 
PPTX
Arrays syntax and it's functions in php.pptx
NikhilVij6
 
PPTX
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
kamalsmail1
 
PPTX
UNIT II (7).pptx
DrDhivyaaCRAssistant
 
PPTX
UNIT II (7).pptx
DrDhivyaaCRAssistant
 
PPTX
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
PPT
Php course-in-navimumbai
vibrantuser
 
PPTX
Tokens in php (php: Hypertext Preprocessor).pptx
BINJAD1
 
PPTX
Presentaion
CBRIARCSC
 
PPTX
07 php
CBRIARCSC
 
PHP tips and tricks
Damien Seguy
 
Php tips-and-tricks4128
PrinceGuru MS
 
PHP record- with all programs and output
KavithaK23
 
Php functions
JIGAR MAKHIJA
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Programmer Blog
 
Php introduction
Osama Ghandour Geris
 
overview of php php basics datatypes arrays
yatakonakiran2
 
07-PHP.pptx
ShishirKantSingh1
 
07-PHP.pptx
GiyaShefin
 
Synapse india complain sharing info about php chaptr 26
SynapseindiaComplaints
 
Arrays syntax and it's functions in php.pptx
NikhilVij6
 
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
kamalsmail1
 
UNIT II (7).pptx
DrDhivyaaCRAssistant
 
UNIT II (7).pptx
DrDhivyaaCRAssistant
 
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Php course-in-navimumbai
vibrantuser
 
Tokens in php (php: Hypertext Preprocessor).pptx
BINJAD1
 
Presentaion
CBRIARCSC
 
07 php
CBRIARCSC
 
Ad

More from tutorialsruby (20)

PDF
&lt;img src="../i/r_14.png" />
tutorialsruby
 
PDF
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
tutorialsruby
 
PDF
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
tutorialsruby
 
PDF
&lt;img src="../i/r_14.png" />
tutorialsruby
 
PDF
&lt;img src="../i/r_14.png" />
tutorialsruby
 
PDF
Standardization and Knowledge Transfer – INS0
tutorialsruby
 
PDF
xhtml_basics
tutorialsruby
 
PDF
xhtml_basics
tutorialsruby
 
PDF
xhtml-documentation
tutorialsruby
 
PDF
xhtml-documentation
tutorialsruby
 
PDF
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
tutorialsruby
 
PDF
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
tutorialsruby
 
PDF
HowTo_CSS
tutorialsruby
 
PDF
HowTo_CSS
tutorialsruby
 
PDF
BloggingWithStyle_2008
tutorialsruby
 
PDF
BloggingWithStyle_2008
tutorialsruby
 
PDF
cascadingstylesheets
tutorialsruby
 
PDF
cascadingstylesheets
tutorialsruby
 
&lt;img src="../i/r_14.png" />
tutorialsruby
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
tutorialsruby
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
tutorialsruby
 
&lt;img src="../i/r_14.png" />
tutorialsruby
 
&lt;img src="../i/r_14.png" />
tutorialsruby
 
Standardization and Knowledge Transfer – INS0
tutorialsruby
 
xhtml_basics
tutorialsruby
 
xhtml_basics
tutorialsruby
 
xhtml-documentation
tutorialsruby
 
xhtml-documentation
tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
tutorialsruby
 
HowTo_CSS
tutorialsruby
 
HowTo_CSS
tutorialsruby
 
BloggingWithStyle_2008
tutorialsruby
 
BloggingWithStyle_2008
tutorialsruby
 
cascadingstylesheets
tutorialsruby
 
cascadingstylesheets
tutorialsruby
 

Recently uploaded (20)

PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PPTX
Simple and concise overview about Quantum computing..pptx
mughal641
 
PPTX
Introduction to Flutter by Ayush Desai.pptx
ayushdesai204
 
PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
PDF
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PPTX
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
PDF
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
Simple and concise overview about Quantum computing..pptx
mughal641
 
Introduction to Flutter by Ayush Desai.pptx
ayushdesai204
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
Doc9.....................................
SofiaCollazos
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 

lab4_php

  • 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.