Metropolitan State University

ICS 325

Internet Application Development

 

Class Notes – Chapter 4&5 – String Manipulation and Functions

 

Often we will want to display text in a specific format for reading and printing ease.

PHP has a wide assortment of tools available for string manipulation

 

String Presentation Functions

           

White space is defined as spaces, tabs, new line, carriage returns, and end of string markers        

Functions to remove white space:

                        trim()               removes white space from a variable

                        ltrim()              removes white space from the start of the variable

                        chop()             removes white space from the end of the variable

           

            Function nl2br takes a string replaces any new line or carriage returns with <br />

 

String Printing Functions

            echo                prints a string to the browser

            print                 prints a string to the browser and returns a Boolean value based on success

            printf                prints a formatted string to the browser

            sprintf              returns a formatted string

           

            Common type codes for printf statements             (See table 4.1 for more examples)

            c          Print as a character

            d          Print as a decimal

            f           Print as a float

            s          Print as a string

 

 

String Formatting Functions

            It is common to have user names case insensitive and passwords case sensitive

            PHP has a verity of functions available for changing case                                   (See table 4.2 for more examples)

                        strtoupper()    changes the characters in the string to all upper case

                        strtolower()     changes the characters in the string to all lower case

 

            Storing formatted strings to a database can cause problems if quotes, nulls, or backslashes are present in the string

            PHP has two built in function to combat these problems

                        AddSlashes()            adds backslashes to the string to be stored

                        StripSlashes()           removes backslashes from the stored string

 

Operations on strings

            Often we want to get a subset of data from a string

            PHP has several functions available for splitting strings, finding substrings, comparing strings, and replacing strings.

            Explode, implode, join, and strtok are all functions for splitting strings

 

Example of using the string tokenizer:

            <?php

$string = "This is\tan example\nstring";

$token = strtok($string," \n\t");

while ($token)      {

      echo "Word = $token<br />"; 

      $token = strtok(" \n\t");

}

 

?>

 

            Portions of strings can be retrieved using the substring function substr()

            The length of a string can be found using the strlen() function

            To find the position of a substring in a string use strpos or strrpos                                                         page 107

            To find a string in a string use strstr(), same as strchr(), or stristr(), which is not case sensitive            page 106

            To replace a string in a string use str_replace() or substr_replace()                                                      page 108

 

           

 

Modularizing Your Programs

 

Code Reuse

Increases consistency

Less work

Enhances reliability – existing code has already been tested

Promotes maintainable code

Reduces costs by reducing amount of code to be maintained

 

Include and Require

Includes and requires allow developers to import multiple pieces code into a single page.

include() – includes a file

require() – same as include() except it produces a fatal error and stops instead of a producing a warning and continuing

 

Examples:

include ("fileName"); 

require ("fileName");

 

Functions

A function is a block of code that can be defined once, and then be invoked from other parts of the program.

Should perform a single, well-defined task.

Allows the programmer to break a complex problem down into small, manageable pieces.

Using functions allows for easier development as multiple programmers can be working on different functions which affect the same program.

Promotes code reuse, consistency and reliability, reduces costs

Function names are not case sensitive (remember that variable names are case sensitive)

 

A function in PHP is defined as:

function function_name (parameter list)     {

            block of code to execute

}

 


Example:

<?php

 

            function squarefeet ($length, $width)          {

                        return $length * $width;

            }

 

            echo (squarefeet(144, 12));

?>

 

Passing Parameters

 

Mechanism for passing input to the function.

 

Pass by value:

A copy of the variable’s value is passed to the function.

The value is known within the function by the formal parameter name.

Changes to the variable within the function are local to the function.  That is, the original variable outside the function is not changed.

 

Pass by reference:

To pass a variable by reference use the & (ampersand) character in front of the formal parameter name.

Pass by reference allows the function to change and return a value via the parameter list.

 

Example:

<?

function grades ($student, $score, &$grade)                    {

            if ($score >= 90 )

                        $grade = 'A';

            else if ($score >= 80 )

                        $grade = 'B';

            else

                        $grade = 'C'; 

}

                                                                   

grades("Bob", 75, $bobsGrade);                                                        

echo "Bob's grade is $bobsGrade<br />";                                                     

?>

 

Optional Parameters:

Default parameter values can be assigned in the parameter list. 

These parameters then become optional when the function is called.

It is not necessary to include all optional parameters.

However, you cannot omit one optional parameter and include a later one.

Optional parameters must be specified last in the parameter list after required parameters.

 

function grades ($student, $grade = “A”)               {

            echo “$student earned an $grade”;  

 }

                                                                    

grades(“Bob”);                                                       

grades(“Bob”, “B”);                                                        

 

            Return

            The return statement can be used to exit a function at any time.

            The return statement can be used to return a value from a function.

            There can be 0, 1 or more return statements in a function.

 

Scope

Global variables cannot be seen inside functions.

Variables local to a function cannot be seen outside the function.

 

 

 

 

Copyright © Jigang Liu, Dave Valentine, Sue Fitzgerald