Top Banner

of 41

php notes bba 2010-13.doc

Apr 02, 2018

Download

Documents

Kunalbhodia
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 7/27/2019 php notes bba 2010-13.doc

    1/41

  • 7/27/2019 php notes bba 2010-13.doc

    2/41

    PHP and MySQL are essential components for running popular content management systems such asDrupal, Joomla!, WordPress and some BitTorrent trackers.

    In your wamp directory you should see the following folders.

    a. apache2 This is where the apache web server is installed. Apache will run our

    php code and scripts on the web browser.

    b. mysql This is where MySql databse is installed. MySQL is an open sourcedatabase. PHP and MySQL work really well together. You can use PHP andMySql to store data.

    c. php You guessed it. This is where php modules are stored.

    d. www This is the root folder of our web server. This is where you are going toput all your php files and scripts.

    e. wampserver.exe This file will run the WAMP program. We need to startWAMP everytime we want to work with PHP.

    f. When you type in http://localhost in your browser, it executes theindex.php file in your www folder. All our php files will go in the wwwfolder.

    Writing php code :

    my php page

    All php code must be embedded within the

    Echo is a special statement in php for outputing data to the browser. This statement is

    more often used when we need to print something to the browser. You will learn how touse echo in as we go along.

    o Echo statement is powerful in a sense that you can put HTML code in it and it

    will render the text as if it was HTML in your browser.

    o echo "hello there!";

    o you cannot use html code inside , except in the echo statement.

    at the end of each PHP statement we need need to put a semicolon, i.e. ";" .Otherwise PHP will report syntax error.

  • 7/27/2019 php notes bba 2010-13.doc

    3/41

    Save this file with .php ext in the www folder and then execute.

    Run it with browser and check the view source

    Echo Examples :

    o Echo simple

    o echo with html

    o echo variables

    o echo with concatenation

    Example : Get system information from PHP

    o

    Variables :

    o Variables are prefixed with a dollar symbol and a type does not need tobe specified in advance.

    o Unlike function and class names, variable names are casesensitive.

    o Every language has its own semantics of defining variables. In PHP, wedefine a variable starting with a $ sign, then write the variable nameand finally assign a value to it.

    o $x = 2; or $x = hello;

    o Var names cannot start with a number. Only letters (upper and lower) ,numbers and underscore is allowed in any var.

    o PHP variables are case sensitive, that means they could be either lower case or

    upper case or combination of both.

    o It is loosely typed language

    o You don't have to worry about declaring the type of the variable. For example

    strings and integers are declared the same way.

    o It's good practice to initialize a variable i.e. assign it a value. Uninitializedvariables in PHP have a value of either false, empty string or empty array.

    o Variables of the "resource" type represent references to resourcesfrom external sources.

    o gettype(var) : returns the type of the variable

    o settype(): sets the type of the var

  • 7/27/2019 php notes bba 2010-13.doc

    4/41

    o Whenconvertingto strings:

    NULL is always converted to an empty string.

    A boolean TRUE value is converted to the string "1". Boolean FALSE isconverted to ""(the empty string) .

    o var_dump(): prints the type and value of a variable

    This function displays structured information about one or more

    expressions that includes its type and value. Arrays and objects areexplored recursively with values indented to show structure.

    The above example will output:

    float(3.1) bool(true)

    It can also be used to display info abt more than one variable at a time.

    o print_r() : is also used to print value of var, arrays as keys and values , objects etc. It does not print

    the type of var only the value.

    Can be explored more in arrays

    Type Juggling

    PHP does not require (or support) explicit type definition in variable declaration; a

    variable's type is determined by the context in which the variable is used. That is tosay, if a string value is assigned to variable $var, $varbecomes a string. If an

    integer value is then assigned to $var, it becomes an integer.

    An example of PHP's automatic type conversion is the addition operator '+'. If either

    operand is a float, then both operands are evaluated as floats, and the result will bea float. Otherwise, the operands will be interpreted as integers, and the result will

    also be an integer.

  • 7/27/2019 php notes bba 2010-13.doc

    5/41

    Note that this does notchange the types of the operands themselves; the onlychange is in how the operands are evaluated and what the type of the expression

    itself is.

    To force a variable to be evaluated as a certain type, To change the type of a variable, use

    settype() function.

    Type Casting

    Type casting in PHP works much as it does in C: the name of the desired type is written inparentheses before the variable which is to be cast.

    The casts allowed are:

    (int), (integer) - cast to integer

    (bool), (boolean) - cast to boolean

    (float), (double), (real) - cast to float

    (string) - cast to string

    (array) - cast to array

    (object) - cast to object

    (unset) - cast to NULL (PHP 5)

    (binary) casting and b prefix forward support was added in PHP 5.2.1

    Note that tabs and spaces are allowed inside the parentheses, so the following arefunctionally equivalent:

  • 7/27/2019 php notes bba 2010-13.doc

    6/41

    Casting literal strings and variables to binary strings:

    Note:

    Instead of casting a variable to a string, it is also possible to enclose the variable in double

    quotes.

    It may not be obvious exactly what will happen when casting between certain types. For

    more information, see these sections:

    Constants :

    o A constant is an identifier (name) for a simple value. As the name suggests,

    that value cannot change during the execution of the script. A constant is

    case-sensitive by default. By convention, constant identifiers are alwaysuppercase.

    o define("FOO", "something");define("FOO2", "something else");

    o all constants are of global scope.

    o All variables are put in the global scope i.e. $GLOBALS array except ifthey are declared in a function.vars inside a function are local.

    Operators :

    o The precedence of an operator specifies how "tightly" it binds two expressions

    together. For example, in the expression 1 + 5 * 3, the answer is 16 and not18 because the multiplication ("*") operator has a higher precedence than the

    addition ("+") operator. Parentheses may be used to force precedence, ifnecessary. For instance: (1 + 5) * 3 evaluates to 18.

    o When operators have equal precedence, their associativity decides whether

    they are evaluated starting from the right, or starting from the left.

  • 7/27/2019 php notes bba 2010-13.doc

    7/41

  • 7/27/2019 php notes bba 2010-13.doc

    8/41

    Pre Increment : $a = ++$i; the value is incremented and then used

    to assign to a.

    o Logical :

    &&, || , and , or

    order of precedence : "||" , '=' and then "or".

    Short circuit operators have greater precedence than normal and , or.

    // The result of the expression (false || true) is assigned to $e

    // Acts like: ($e = (false || true))

    $e = false || true;

    // The constant false is assigned to $f and then true is ignored coz of

    = having higher prec

    // Acts like: (($f = false) or true)

    $f = false or true;

    Loops : for, while, do while

    Conditional statements : if, nested if, if else if

    Control structures :

    o breakends execution of the current for, foreach, while, do-while or switch

    structure.

    o breakaccepts an optional numeric argument which tells it how many nested

    enclosing structures are to be broken out of.

    o while (++$i) {switch ($i) {case 5:

    echo "At 5
    \n";break 1; /* Exit only the switch. */ case 10:

    echo "At 10; quitting
    \n";break 2; /* Exit the switch and the while. */

    default:break;

    }}

  • 7/27/2019 php notes bba 2010-13.doc

    9/41

    o Switch:

    In a switch statement, the condition is evaluated only once and theresult is compared to each case statement. In an elseifstatement, the

    condition is evaluated again. If your condition is more complicatedthan a simple compare and/or is in a tight loop, a switch may be

    faster.

    o The case expression may be any expression that evaluates to a simple type,

    that is, integer or floating-point numbers and strings. Arrays or objectscannot be used here unless they are dereferenced to a simple type.

    Forms :

    o The PHP $_REQUEST Function : The PHP built-in $_REQUEST function

    contains the contents of both $_GET, $_POST, and $_COOKIE. The

    $_REQUEST function can be used to collect form data sent with both the GETand POST methods.

    o $_POST : The built-in $_POST function is used to collect values from a form

    sent with method="post". Information sent from a form with the POST

    method is invisible to others and has no limits on the amount of informationto send. However, there is an 8 Mb max size for the POST method, by default

    (can be changed by setting the post_max_size in the php.ini file).

    o $_GET : The built-in $_GET function is used to collect values from a form

    sent with method="get". Information sent from a form with the GET methodis visible to everyone (it will be displayed in the browser's address bar) and

    has limits on the amount of information to send.

    User defined Functions :

    o A function may be defined using syntax such as the following:

  • 7/27/2019 php notes bba 2010-13.doc

    10/41

    o function foo($arg_1, $arg_2, /* ..., */ $arg_n){

    echo "Example function.\n";return $retval;

    }

    o Any valid PHP code may appear inside a function, even other functions andclass definitions

    o Sequence of function definition and function call does not matter. You can

    call it in your program before its definition in the php file, but the

    definition must exist at a later point.

    o

    o Nested functions :

    function foo(){

    function bar(){

    echo "I don't exist until foo() is called.\n";}

    }

    /* We can't call bar() yetsince it doesn't exist. */

    foo(); // only foo() and not bar() will be executed

    /* Now we can call bar(),foo()'s processesing has

    made it accessible. */

    bar();

    All functions and classes in PHP have the global scope - they can be

    called outside a function even if they were defined inside and viceversa.

    PHP does not support function overloading

    Pass by value / reference : By default, function arguments are passed by value

    (so that if the value of the argument within the function is changed, it does not get

    changed outside of the function). To allow a function to modify its arguments, they

    must be passed by reference.

    o To have an argument to a function always passed by reference, prepend an

    ampersand (&) to the argument name in the function definition

    o See fnDemo.php

  • 7/27/2019 php notes bba 2010-13.doc

    11/41

    Use of default parameters in functions : if u specify a default value, it is allowed

    to call a function without any arguments.

    o You can also pass null or array elements as default value

    o function makecoffee($type = "cappuccino"){

    return "Making a cup of$type.\n";}s

    o The default value must be a constant expression, not (for example) a

    variable, a class member or a function call.

    o Note that when using default arguments, any defaults should be on the right

    side of any non-default arguments; otherwise things will not work as

    expected

    o if you do not supply any argument in fn call but an arg exists as per

    fn defintion without any default value, it gives a warning not an error.

    If the arg has been given a default value in the fn definition, then it

    uses the default value.

    o

    Returning values :Values are returned by using the optional return statement

    o Any type may be returned, including arrays and objects.

    o This causes the function to end its execution immediately and pass control

    back to the line from which it was called.

    o If the return() is omitted the value NULL will be returned.

    o If, you want to return multiple values, use an array. But return statement

    cannot be repeated in a function, it can occur only once.

    Variable functions : PHP supports the concept of variable functions. This meansthat if a variable name has parentheses appended to it, PHP will look for a function

    with the same name as whatever the variable evaluates to, and will attempt toexecute it. Among other things, this can be used to implement callbacks, function

    tables, and so forth.

    o $func = 'foo'; // a variable $func

    $func(); // This calls foo() after evaluating value of var

    $func = 'bar';$func('test'); // This calls bar()

    Functions need not be defined before they are referenced, exceptwhen a function

    is conditionally defined as shown in the two examples below.

  • 7/27/2019 php notes bba 2010-13.doc

    12/41

    When a function is defined in a conditional manner such as the example shown. Its

    definition must be processedpriorto being called.

    if ($makefoo) {function foo(){

    echo "I don't exist until program execution reaches me.\n";}

    }

    after this if loop we can call foo()

    Arrays :o An array is a special variable, which can store multiple values in one single variable.

    o In PHP, there are three kind of arrays:

    Numeric array - An array with a numeric index

    Associative array

    An array can be created by the array() language construct. It

    takes as parameters any number of comma-separated key =>value pairs.

    array( key => value

    , ...

    ) // key may only be an integer or stringy

    // value may be any value of any type

    An array where each ID key is associated with a value. Key cannot be

    repeated but value can.

    PHP automatically uses incrementing numbers for array keys

    when you create an array or add elements to an array with the

    empty brackets syntax.

    $asc_arr = array("bca" => 121 , "bba" => 122 , "msc" => 141,

    "mba" => 142);

    //alternate way

    $asc_arr['bba']=122;

    Floats in keyare truncated to integer.

  • 7/27/2019 php notes bba 2010-13.doc

    13/41

    Multidimensional array - An array containing one or more arrays

    Another way to add elements in the array is by equating the string to be inserted

    with the array variable: this element will be added to the end as it is the emptyindex.

    $arrayvariable[]="String to be inserted to the array

    But if you write $arrayvariable = hello; then preivuos elements of thearray will be overwritten and it will now contain only one str, as indexnot specified so it is like equating a new array to the old one.

    o Array Functions : count(array,mode) :

    array Required. Specifies the array or object to count.

    mode Optional. Specifies the mode of the function. Possiblevalues:

    0 - Default. Does not detect multidimensional

    arrays (arrays within arrays)

    1 - Detects multidimensional arrays

    Note: This parameter was added in PHP 4.2

    ksort(array,sorttype) : The ksort() function sorts an array by the keys. Thevalues keep their original keys.

    Parameter Description

    array Required. Specifies the array to sort

    sorttype Optional. Specifies how to sort the array values. Possible values:

    SORT_REGULAR - Default. Treat values as they are (don't

    change types)

    SORT_NUMERIC - Treat values numerically

    SORT_STRING - Treat values as strings

    SORT_LOCALE_STRING - Treat values as strings, based on

    local settings

    Sort() : The sort() function sorts an array by the values. This functionassigns new keys for the elements in the array. Existing keys will be

    removed

    rsort() : Sorts an array in reverse order

    in_array(search,array,type) : The in_array() function searches an

    array for a specific value. This function returns TRUE if the value is found inthe array, or FALSE otherwise.

    Parameter Description

  • 7/27/2019 php notes bba 2010-13.doc

    14/41

    search Required. Specifies the what to search for

    array Required. Specifies the array to search

    type Optional. If this parameter is set, the in_array() functionsearches for the search-string and specific type in thearray

    array_push(array,value1,value2...) : The array_push() function inserts one or

    more elements to the end of an array.

    Parameter Description

    array Required. Specifies an array

    value1 Required. Specifies the value to add

    value2 Optional. Specifies the value to add

    array_pop(array) : deletes last element of the array

    array_slice(array,start,length,preserve) :The array_slice() functionreturns selected parts of an array. The original contents of arrayremain unchanged.

    If the array have string keys, the returned array will allways preserve

    the keys. For other numeric keys, the preserve parameter shud be setto true for preserving keys, else returned arr will hv new keys

    array Required. Specifies an array

    start Required. Numeric value. Specifies where the function will startthe slice. 0 = the first element. If this value is set to a negative

    number, the function will start slicing that far from the lastelement. -2 means start at the second last element of the array.

    length Optional. Numeric value. Specifies the length of the returnedarray. If this value is set to a negative number, the function will

    stop slicing that far from the last element. If this value is not

    set, the function will return all elements, starting from theposition set by the start-parameter.

    preserve Optional. Possible values:

    true - Preserve keysfalse - Default - Reset keys

    array_splice(array,start,length,array) :The array_splice() functionremoves selected elements from an array and replaces it with newelements. The function also returns an array with the removedelements.

    Parameter Description

    array Required. Specifies an array

    start Required. Numeric value. Specifies where the functionwill start removing elements. 0 = the first element. If

    this value is set to a negative number, the function will

    start that far from the last element. -2 means start atthe second last element of the array.

    length Optional. Numeric value. Specifies how many elements

    will be removed, and also length of the returned array.If this value is set to a negative number, the function

    will stop that far from the last element. If this value is

  • 7/27/2019 php notes bba 2010-13.doc

    15/41

    not set, the function will remove all elements, starting

    from the position set by the start-parameter.

    array Optional. Specifies an array with the elements that willbe inserted to the original array. If it's only one

    element, it can be a string, and does not have to be an

    array. array_merge(array1,array2,array3...) : function merges one ore

    more arrays into one array

    array_shift() : shifts the first value of the arrayoff and returns it,shortening the arrayby one element and moving everything down.Allnumerical array keys will be modified to start counting from zero while

    literal keys won't be touched.

    array_search() : Searches an array for a given value and returns thekey.

    array_search(value,array,strict) :

    Output is b.

    unset($arr[5]); // This removes the element from the array. Thesize of the array also decreases.

    Unlike pop which deleted only the last element, you can use

    unset to delete any element at any position in the array.

    Unset can be used to delete any normal variable which is not in

    an array.

    ParameterDescription

    value Required. Specifies the value to search for

    array Required. Specifies the array to search in

    strict Optional. Possible values:

    true

    false - Default

    When set to true, the number 5 is not the

    same as the string 5 (See example 2)

  • 7/27/2019 php notes bba 2010-13.doc

    16/41

    unset($arr); // This deletes the whole array

    only using unset on an associative or a non associative array

    does not re index the array. The entire value and key is

    removed for an associative array.

    so if index 2 is removed, the array has indexes 0,1,3 and 4 you

    can then reassign value to the index 2 which was unset earlier

    isset : Determine if a variable is set and is not NULL

    array_values : The unset() function allows removing keys from an

    array. Be aware that the array will notbe reindexed. If a true"remove and shift" behavior is desired, the array can be reindexed

    using the array_values() function.

    array array_values ( array $input) : returns all the values

    from the inputarray and indexes numerically the array.It willremove any user given indexed and put the deafult o,1,2

    indexes.

    array_keys() returns the keys, numeric and string, from the inputarray.

    array_keys(array,search_value,strict)

    o search_value : returns only those keys who have value

    that matches the search_value entered. If specified,then only keys containing these values are returned.

    o strict : Determines if strict comparison (===) should be

    used during the search

    o the search_value and strict parameter are optional.

    o keys are returned as a array of keys.

    For a non associative array, the array_keys fnction

    returns the position/index of the key being searched.

    array_key_exists() returns TRUE if the given keyis set in the array.keycan be any value possible for an array index

    array_key_exists(value,$arr) : will return true if the value

    exists in the $arr else returns false.

    in_array : Checks if a value exists in an array.

  • 7/27/2019 php notes bba 2010-13.doc

    17/41

    in_array(value,array,strict) : searches for the given value in the

    given array. If strict is set to true it matches the data type also.

    If strict is false, data type is not matched, only values are. So 5will be considered equal to 5 if strict is false.

    array_combine :

    array_combine (array $keys , array $values )

    Creates an array by using the values from the keys array as keys andthe values from the values array as the corresponding values.

    Returns the combined array, FALSE if the number of elements foreach array isn't equal.

    string implode ( string $glue , array $pieces ) :

    join array elements with a string

    Returns a string containing a string representation of all thearray elements in the same order, with the glue string betweeneach element.

    $array = array('lastname', 'email', 'phone');

    $comma_separated = implode(",", $array);

    array explode ( string $delimiter, string $string [, int $limit] )

    Returns an array of strings, each of which is a substring of

    string formed by splitting it on boundaries formed by the stringdelimiter.

    Iflimitis set and positive, the returned array will contain a

    maximum oflimitelements with the last element containing therest ofstring.

    If the limitparameter is negative, all components except the

    last -limitare returned.

    If the limitparameter is zero, then this is treated as 1.

    asort Sort an array based on its values and maintain index

    association.

    asort($arr);

    o For multidimensional arrays, refer to class program

    File Handling :

  • 7/27/2019 php notes bba 2010-13.doc

    18/41

    In php u can, create a file by directly opening it using the correct

    mode or using

    Read: 'r'

    Open a file for read only use. The file pointer begins at the front of the file.

    Write: 'w'

    Open a file for write only use. In addition, the data in the file is erased and you will begin

    writing data at the beginning of the file. This is also called truncating a file, which we will

    talk about more in a later lesson. The file pointer begins at the start of the file.

    Append: 'a'

    Open a file for write only use. However, the data in the file is preserved and you begin will

    writing data at the end of the file. The file pointer begins at the end of the file.

    A file pointeris PHP's way of remembering its location in a file.

    Read/Write: 'r+'

    Opens a file so that it can be read from and written to. The file pointer is at the

    beginning of the file.

    Write/Read: 'w+'

    This is exactly the same as r+, except that it deletes all information in the file when

    the file is opened.

    Append: 'a+'

    This is exactly the same as r+, except that the file pointer is at the end of the file.

    A list of possible modes for fopen() using modemod

    e Description

    'r'Open for reading only; place the file pointer at the beginning of

    the file.

    'r+'Open for reading and writing; place the file pointer at thebeginning of the file.

    'w'Open for writing only; place the file pointer at the beginning ofthe file and truncate the file to zero length. If the file does notexist, attempt to create it.

    'w+ Open for reading and writing; place the file pointer at the

  • 7/27/2019 php notes bba 2010-13.doc

    19/41

    A list of possible modes for fopen() using modemod

    e Description

    'beginning of the file and truncate the file to zero length. If the filedoes not exist, attempt to create it.

    'a' Open for writing only; place the file pointer at the end of the file.If the file does not exist, attempt to create it.

    'a+'Open for reading and writing; place the file pointer at the end ofthe file. If the file does not exist, attempt to create it.

    'x'

    Create and open for writing only; place the file pointer at thebeginning of the file. If the file already exists, the fopen() call willfail by returning FALSE and generating an error of levelE_WARNING. If the file does not exist, attempt to create it. This isequivalent to specifying O_EXCL|O_CREATflags for the underlyingopen(2) system call.

    'x+' Create and open for reading and writing; otherwise it has thesame behavior as 'x'.

    'c'

    Open the file for writing only. If the file does not exist, it iscreated. If it exists, it is neither truncated (as opposed to 'w'), northe call to this function fails (as is the case with 'x'). The filepointer is positioned on the beginning of the file. This may beuseful if it's desired to get an advisory lock (see flock()) beforeattempting to modify the file, as using 'w'could truncate the filebefore the lock was obtained (if truncation is desired, ftruncate()can be used after the lock is requested).

    'c+' Open the file for reading and writing; otherwise it has the samebehavior as 'c'.

    o Creating and deleting files:

    You can create a file by using the fopen function in the appropriate

    mode.

    fopen(new.txt,w+)

    You can remove an existing file with the unlink() function.

    unlink() accepts a file path:

    unlink(file.txt);

    file_exists() : If the file is found, file_exists(myfile.txt) returns true;

    otherwise, it returns false.

    http://in3.php.net/manual/en/function.flock.phphttp://in3.php.net/manual/en/function.ftruncate.phphttp://in3.php.net/manual/en/function.ftruncate.phphttp://in3.php.net/manual/en/function.flock.php
  • 7/27/2019 php notes bba 2010-13.doc

    20/41

    is_file() : You can confirm that the entity you're testing is a file, as

    opposed to a directory, with the, is_file() function.is_file() takes one argument, which is the file path and returns a

    Boolean value.

    Example : if (is_file(file.jpg)) {

    print file.jpg is a file; }

    is_dir() : checks for dir

    o Reading lines from a file: To read a line from an open file, you can use

    fgets().

    fgets() requires the file resource returned from fopen() as anargument.

    You may also pass fgets() an integer as a second argument.

    The integer argument specifies the number of bytes that the

    function should read if it doesn't first encounter a line end orthe end of the file.

    o fgets() reads the file until it reaches a newline character

    ("\n"), the number of bytes specified in the lengthargument, or the end of the file.

    $line = fgets($fp, 1024);

    feof($fp) : The feof() function does this by returning true when

    the end of the file has been reached and false otherwise. feof()requires a file resource as its argument.

    fgetc Gets character from file pointer

    Fread reads a specified number of characters from the file

    fread($fp, 7);

    fwrite($fp, string, length) : accepts a file resource and a string, and then writes the

    string to the file.

    $fp : file handle of the file into which you are writing

    String : is the string data to be written to the file

    length ; optional parameter. Length of data to be written. If

    the length argument is given, writing will stopafter length bytes have been written or the end of string is

    reached, whichever comes first.

    fwrite() returns the number of bytes written, or FALSE on error.

  • 7/27/2019 php notes bba 2010-13.doc

    21/41

    fputs() works in exactly the same way. alias of fwrite.

    filesize(filename) : takes filename and NOT the resource handle

    filetype Gets file type

    file Reads entire file into an array

    array file ( string $filename [, int $flags = 0 [, resource $context]])

    The optional parameter flags can be one, or more, of the followingconstants:

    FILE_USE_INCLUDE_PATH - Search for the file in the include_path.

    FILE_IGNORE_NEW_LINES - Do not add newline at the end of each

    array element

    FILE_SKIP_EMPTY_LINES - Skip empty lines

    fileatime Gets last access time of file

    fseek Seeks on a file pointer.

    int fseek ( resource $handle , int $offset[, int $whence =

    SEEK_SET] )

    Sets the file position indicator for the file referenced by handle. The

    new position, measured in bytes from the beginning of the file, is

    obtained by adding offsetto the position specified by whence.

    whence values are:

    o SEEK_SET - Set position equal to offsetbytes.

    o SEEK_CUR - Set position to current location plus offset.

    SEEK_END - Set position to end-of-file plus offset.

    Strings :

    o strlen() : The strlen() function is used to return the length of a string.

    o strpos() : The strpos() function is used to search for a character/text within a string. If a

    match is found, this function will return the character position of the first match. If nomatch is found, it will return FALSE.

    echo strpos("Hello world!","world"); // output is 6

    int strpos ( string $haystack, mixed$needle [, int $offset= 0 ] )

    http://www.php.net/manual/en/language.pseudo-types.php#language.types.mixedhttp://www.php.net/manual/en/language.pseudo-types.php#language.types.mixed
  • 7/27/2019 php notes bba 2010-13.doc

    22/41

    The optional offsetparameter allows you to specify which character in thestring to start searching.

    o strrpos Find the position of the last occurrence of a substring in a string

    int strrpos ( string $haystack, string $needle [, int $offset= 0 ] )

    o substr :

    string substr ( string $string , int $start[, int $length ] )

    Returns the portion ofstring specified by the startand length parameters.

    Start :

    Ifstartis negative, the returned string will start at

    the start'th character from the end ofstring.

    Ifstring is less than or equal to startcharacters

    long, FALSE will be returned.

    $rest = substr("abcdef", -1); // returns "f"

    $rest = substr("abcdef", -2); // returns "ef"$rest = substr("abcdef", -3, 1); // returns "d"

    Length :

    Iflength is given and is negative, then that many characters will beomitted from the end ofstring (after the start position has beencalculated when a startis negative). Ifstartdenotes the position ofthis truncation or beyond, false will be returned.

    Iflength is given and is 0, FALSE or NULL an empty string will be

    returned.

    Iflength is omitted, the substring starting from startuntil the end ofthe string will be returned.

    $rest = substr("abcdef", 0, -1); // returns "abcde"

    $rest = substr("abcdef", 2, -1); // returns "cde"$rest = substr("abcdef", 4, -4); // returns false

    o trim(string) - This function removes the whitespaces from bothstart and the end of the string. Length does not change in trimfunction. It does not remove the spaces in between.

    Ex : $a = a bc;

    trim($a); // output is a bc. Only the starting and endingspaces are removed

    o ltrim(string) : This function removes the whitespaces from theleft part of the string.

  • 7/27/2019 php notes bba 2010-13.doc

    23/41

    o rtrim(string) :This function removes the whitespaces from theright part of the string.

    o strtolower(string) - This function converts the string to lowercase

    o strtoupper(string) - This function converts the string to uppercase

    o str_replace str_replace(search, replace, string/array,[count])

    search : is the value that is to be searched in the givenstring. Can be an array as well.

    replace : the value to be replaced in place of search. Can bean array as well.

    subject : The string on which the search and replace is to be carried out. If it isan array of strings, search and replace will be done on each element of the

    array. Ifsubjectis an array, then the search and replace is performedwith every entry ofsubject, and the return value is an array as well.So the original array remains unchanged

    The str_replace() function replaces some characters withsome other characters in a string.This function works by the following rules:

    If the string to be searched is an array, it returns an array If the string to be searched is an array, find and replace is

    performed with every array element If both find and replace are arrays, and replace has fewer

    elements than find, an empty string will be used as replace If find is an array and replace is a string, the replace string

    will be used for every find value print_r(str_replace("red","pink",$arr,$i)); echo $i; // output = 1 as only 1 replacement was done

    o strcmp(string1, string2) :The strcmp() function compares twostrings.

    Returns

    0 if the two strings are equal Negative or 0 if string1 is greater than string2

    The strcmp() function is binary safe and case-sensitive.

  • 7/27/2019 php notes bba 2010-13.doc

    24/41

    For case insensitive comparison you can usestrcasecmp(,); function. It is similar tostrcmp() function.

    Date time functions:

    date(string format) :

    The following characters are recognized in the formatparameter string

    format

    character DescriptionExample returned

    values

    Day --- ---

    dDay of the month, 2 digitswith leading zeros

    01 to 31

    D A textual representation ofa day, three letters

    Mon through Sun

    jDay of the month withoutleading zeros

    1 to 31

    l(lowercase'L')

    A full textual representationof the day of the week

    SundaythroughSaturday

    N

    ISO-8601 numericrepresentation of the day ofthe week (added in PHP5.1.0)

    1 (for Monday)through 7(for Sunday)

    SEnglish ordinal suffix for theday of the month, 2characters

    st, nd, rdor th. Workswell withj

    wNumeric representation ofthe day of the week

    0 (for Sunday)through 6 (forSaturday)

    zThe day of the year(starting from 0)

    0 through 365

    Week --- ---

    W

    ISO-8601 week number ofyear, weeks starting onMonday (added in PHP4.1.0)

    Example: 42 (the42nd week in the year)

    Month --- ---

  • 7/27/2019 php notes bba 2010-13.doc

    25/41

    The following characters are recognized in the format

    parameter string

    format

    character DescriptionExample returned

    values

    FA full textual representationof a month, such as Januaryor March

    JanuarythroughDecember

    mNumeric representation of amonth, with leading zeros

    01 through 12

    MA short textualrepresentation of a month,three letters

    Jan through Dec

    nNumeric representation of amonth, without leadingzeros

    1 through 12

    tNumber of days in thegiven month

    28 through 31

    Year --- ---

    L Whether it's a leap year1 if it is a leap year, 0otherwise.

    o

    ISO-8601 year number.This has the same value asY, except that if the ISOweek number (W) belongs

    to the previous or nextyear, that year is usedinstead. (added in PHP5.1.0)

    Examples: 1999 or

    2003

    YA full numericrepresentation of a year, 4digits

    Examples: 1999 or2003

    yA two digit representationof a year

    Examples: 99 or 03

    Time --- ---

    aLowercase Ante meridiemand Post meridiem

    am orpm

    AUppercase Ante meridiemand Post meridiem

    AMor PM

    B Swatch Internet time 000 through 999

  • 7/27/2019 php notes bba 2010-13.doc

    26/41

    The following characters are recognized in the format

    parameter string

    format

    character DescriptionExample returned

    values

    g12-hour format of an hourwithout leading zeros 1 through 12

    G24-hour format of an hourwithout leading zeros

    0 through 23

    h12-hour format of an hourwith leading zeros

    01 through 12

    H24-hour format of an hourwith leading zeros

    00 through 23

    i Minutes with leading zeros 00 to 59

    s Seconds, with leading zeros 00 through 59

    uMicroseconds (added in PHP5.2.2)

    Example: 654321

    Timezone --- ---

    eTimezone identifier (addedin PHP 5.1.0)

    Examples: UTC, GMT,Atlantic/Azores

    I(capital i)Whether or not the date isin daylight saving time

    1 if Daylight SavingTime, 0 otherwise.

    ODifference to Greenwichtime (GMT) in hours Example: +0200

    P

    Difference to Greenwichtime (GMT) with colonbetween hours and minutes(added in PHP 5.1.3)

    Example: +02:00

    T Timezone abbreviationExamples: EST,MDT...

    Z

    Timezone offset in seconds.The offset for timezoneswest of UTC is always

    negative, and for those eastof UTC is always positive.

    -43200 through

    50400

  • 7/27/2019 php notes bba 2010-13.doc

    27/41

    The following characters are recognized in the format

    parameter string

    format

    character DescriptionExample returned

    values

    FullDate/Time

    --- ---

    c ISO 8601 date (added inPHP 5)

    2004-02-12T15:19:21+00:00

    r RFC 2822 formatted dateExample: Thu, 21 Dec2000 16:01:07 +0200

    USeconds since the UnixEpoch (January 1 197000:00:00 GMT)

    See also time()

    time() : returns the unix timestamp for the current time.

    o Unix timestamp: The unix time stamp is a way to track timeas a running total of seconds. This count starts at theUnix Epoch on January 1st, 1970. Therefore, the unix timestamp is merely the number of seconds between a particulardate and the Unix Epoch. This is very useful to computersystems for tracking and sorting dated information indynamic and distributed applications both online and clientside

    cal_days_in_month(calendar_type, month number, year) : Return the number

    of days in a month for a given year and calendar

    cal_info(int calendar_type) : Returns information about a particular calendar

    o Calendar information is returned as an array containing the elements alname,

    calsymbol, month, abbrevmonth and maxdaysinmonth. The names of thedifferent calendars which can be used as calendar_type are as follows:

    0 or CAL_GREGORIAN - Gregorian Calendar

    http://www.faqs.org/rfcs/rfc2822http://www.php.net/manual/en/function.time.phphttp://www.faqs.org/rfcs/rfc2822http://www.php.net/manual/en/function.time.php
  • 7/27/2019 php notes bba 2010-13.doc

    28/41

    1 or CAL_JULIAN - Julian Calendar

    2 or CAL_JEWISH - Jewish Calendar

    3 or CAL_FRENCH - French Revolutionary Calendar

    If no calendaris specified information on all supported calendars is returnedas an array.

    Error handling:

    In php there are three error handling types

    o Simple "die()" statements

    o Custom errors and error triggers :

    Creating a custom error handler is simple. We simply create a special function that can be called

    when an error occurs in PHP.

    This function must be able to handle a minimum of two parameters (error level and error

    message) but can accept up to five parameters (optionally: file, line-number, and the errorcontext)

    error_function(error_level,error_message,error_file,error_line,error_context)

    error_level Required. Specifies the error report level for the user-definederror. Must be a value number. See table below for possibleerror report levels

    error_message Required. Specifies the error message for the user-definederror

    error_file Optional. Specifies the filename in which the error occurred

    error_line Optional. Specifies the line number in which the error occurred

    error_context Optional. Specifies an array containing every variable, andtheir values, in use when the error occurred

    These error report levels are the different types of error the user-defined error handler can beused for:

    Value Constant Description Note

    1 E_ERROR (integer)

    Fatal run-time errors. These

    indicate errors that can not be

    recovered from, such as a memory

    allocation problem. Execution of

    the script is halted.

    2 E_WARNING Run-time warnings (non-fatal

    errors). Execution of the script is

  • 7/27/2019 php notes bba 2010-13.doc

    29/41

    Value Constant Description Note

    (integer) not halted.

    4 E_PARSE (integer)

    Compile-time parse errors. Parse

    errors should only be generated by

    the parser.

    8 E_NOTICE (integer)

    Run-time notices. Indicate that the

    script encountered something that

    could indicate an error, but could

    also happen in the normal course of

    running a script.

    16E_CORE_ERROR

    (integer)

    Fatal errors that occur during PHP's

    initial startup. This is like an

    E_ERROR, except it is generated bythe core of PHP.

    since PHP 4

    32E_CORE_WARNING

    (integer)

    Warnings (non-fatal errors) that

    occur during PHP's initial startup.

    This is like an E_WARNING, except

    it is generated by the core of PHP.

    since PHP 4

    64E_COMPILE_ERROR

    (integer)

    Fatal compile-time errors. This is

    like an E_ERROR, except it is

    generated by the Zend Scripting

    Engine.

    since PHP 4

    128E_COMPILE_WARNIN

    G (integer)

    Compile-time warnings (non-fatal

    errors). This is like an E_WARNING,

    except it is generated by the Zend

    Scripting Engine.

    since PHP 4

    256E_USER_ERROR

    (integer)

    User-generated error message.

    This is like an E_ERROR, except it is

    generated in PHP code by using the

    PHP function trigger_error().

    since PHP 4

    512E_USER_WARNING

    (integer)

    User-generated warning message.

    This is like an E_WARNING, except

    it is generated in PHP code by using

    the PHP function trigger_error().

    since PHP 4

    1024 E_USER_NOTICE User-generated notice message. since PHP 4

  • 7/27/2019 php notes bba 2010-13.doc

    30/41

    Value Constant Description Note

    (integer)

    This is like an E_NOTICE, except it

    is generated in PHP code by using

    the PHP function trigger_error().

    2048 E_STRICT (integer)

    Enable to have PHP suggest

    changes to your code which will

    ensure the best interoperability and

    forward compatibility of your code.

    since PHP 5

    4096E_RECOVERABLE_ER

    ROR (integer)

    Catchable fatal error. It indicates

    that a probably dangerous error

    occured, but did not leave the

    Engine in an unstable state. If the

    error is not caught by a user

    defined handle (see also

    set_error_handler()), the

    application aborts as it was an

    E_ERROR.

    since PHP

    5.2.0

    8192E_DEPRECATED

    (integer)

    Run-time notices. Enable this to

    receive warnings about code that

    will not work in future versions.

    since PHP

    5.3.0

    16384E_USER_DEPRECATE

    D (integer)

    User-generated warning message.

    This is like an E_DEPRECATED,except it is generated in PHP code

    by using the PHP function

    trigger_error().

    since PHP5.3.0

    30719 E_ALL (integer)

    All errors and warnings, as

    supported, except of level

    E_STRICT.

    30719 in PHP

    5.3.x, 6143 in

    PHP 5.2.x,

    2047

    previously

    The above values (either numerical or symbolic) are used to build up a bitmask thatspecifies which errors to report. You can use the bitwise operators to combine thesevalues or mask out certain types of errors. Note that only '|', '~', '!', '^' and '&' will be

    understood withinphp.ini.

  • 7/27/2019 php notes bba 2010-13.doc

    31/41

    o PHP supports one error control operator: the at sign (@). When prepended to an

    expression in PHP, any error messages that might be generated by that

    expression will be ignored.

    Error reporting : The error_reporting() function sets the error_reporting directive atruntime. PHP has many levels of errors, using this function sets that level for the duration

    (runtime) of your script. If the optional level is not set, error_reporting() will just return thecurrent error reporting level.

    o // Report simple running errorserror_reporting(E_ERROR | E_WARNING | E_PARSE);

    o // Report all errors except E_NOTICE// This is the default value set in php.inierror_reporting(E_ALL ^ E_NOTICE);

    o The following error types cannot be handled with a user defined function:E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING,E_COMPILE_ERROR, E_COMPILE_WARNING, and most ofE_STRICT raised in

    the file where set_error_handler() is called.

    Date time functions:

    date(string format) :

    The following characters are recognized in the formatparameter string

    format

    character DescriptionExample returned

    values

    Day --- ---

    dDay of the month, 2 digitswith leading zeros

    01 to 31

    DA textual representation ofa day, three letters

    Mon through Sun

    jDay of the month withoutleading zeros

    1 to 31

    l(lowercase'L')

    A full textual representationof the day of the week

    SundaythroughSaturday

    N

    ISO-8601 numeric

    representation of the day ofthe week (added in PHP5.1.0)

    1 (for Monday)through 7(for Sunday)

    SEnglish ordinal suffix for theday of the month, 2characters

    st, nd, rdor th. Workswell withj

    http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reportinghttp://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting
  • 7/27/2019 php notes bba 2010-13.doc

    32/41

    The following characters are recognized in the format

    parameter string

    format

    character DescriptionExample returned

    values

    w Numeric representation ofthe day of the week

    0 (for Sunday)through 6 (forSaturday)

    zThe day of the year(starting from 0)

    0 through 365

    Week --- ---

    W

    ISO-8601 week number ofyear, weeks starting onMonday (added in PHP4.1.0)

    Example: 42 (the42nd week in the year)

    Month --- ---

    FA full textual representationof a month, such as Januaryor March

    JanuarythroughDecember

    mNumeric representation of amonth, with leading zeros

    01 through 12

    MA short textualrepresentation of a month,three letters

    Jan through Dec

    nNumeric representation of amonth, without leadingzeros

    1 through 12

    tNumber of days in thegiven month

    28 through 31

    Year --- ---

    L Whether it's a leap year1 if it is a leap year, 0otherwise.

    o

    ISO-8601 year number.

    This has the same value asY, except that if the ISOweek number (W) belongsto the previous or nextyear, that year is usedinstead. (added in PHP5.1.0)

    Examples: 1999 or2003

  • 7/27/2019 php notes bba 2010-13.doc

    33/41

    The following characters are recognized in the format

    parameter string

    format

    character DescriptionExample returned

    values

    YA full numericrepresentation of a year, 4digits

    Examples: 1999 or2003

    yA two digit representationof a year

    Examples: 99 or 03

    Time --- ---

    aLowercase Ante meridiemand Post meridiem

    am orpm

    AUppercase Ante meridiemand Post meridiem

    AMor PM

    B Swatch Internet time 000 through 999

    g12-hour format of an hourwithout leading zeros

    1 through 12

    G24-hour format of an hourwithout leading zeros

    0 through 23

    h12-hour format of an hourwith leading zeros

    01 through 12

    H24-hour format of an hourwith leading zeros

    00 through 23

    i Minutes with leading zeros 00 to 59

    s Seconds, with leading zeros 00 through 59

    uMicroseconds (added in PHP5.2.2)

    Example: 654321

    Timezone --- ---

    eTimezone identifier (addedin PHP 5.1.0)

    Examples: UTC, GMT,Atlantic/Azores

    I(capital i)Whether or not the date isin daylight saving time

    1 if Daylight SavingTime, 0 otherwise.

    ODifference to Greenwichtime (GMT) in hours

    Example: +0200

    P Difference to Greenwichtime (GMT) with colonbetween hours and minutes

    Example: +02:00

  • 7/27/2019 php notes bba 2010-13.doc

    34/41

    The following characters are recognized in the format

    parameter string

    format

    character DescriptionExample returned

    values

    (added in PHP 5.1.3)

    T Timezone abbreviationExamples: EST,MDT...

    Z

    Timezone offset in seconds.The offset for timezoneswest of UTC is alwaysnegative, and for those eastof UTC is always positive.

    -43200 through50400

    FullDate/Time

    --- ---

    cISO 8601 date (added in

    PHP 5)

    2004-02-

    12T15:19:21+00:00

    r RFC 2822 formatted dateExample: Thu, 21 Dec2000 16:01:07 +0200

    USeconds since the UnixEpoch (January 1 197000:00:00 GMT)

    See also time()

    time() : returns the unix timestamp for the current time.

    o Unix timestamp: The unix time stamp is a way to track timeas a running total of seconds. This count starts at theUnix Epoch on January 1st, 1970. Therefore, the unix timestamp is merely the number of seconds between a particulardate and the Unix Epoch. This is very useful to computersystems for tracking and sorting dated information indynamic and distributed applications both online and clientside

    http://www.faqs.org/rfcs/rfc2822http://www.php.net/manual/en/function.time.phphttp://www.faqs.org/rfcs/rfc2822http://www.php.net/manual/en/function.time.php
  • 7/27/2019 php notes bba 2010-13.doc

    35/41

    cal_days_in_month(calendar_type, month number, year) : Return the numberof days in a month for a given year and calendar

    cal_info(int calendar_type) : Returns information about a particular calendar

    o Calendar information is returned as an array containing the elements alname,

    calsymbol, month, abbrevmonth and maxdaysinmonth. The names of thedifferent calendars which can be used as calendar_type are as follows:

    0 or CAL_GREGORIAN - Gregorian Calendar

    1 or CAL_JULIAN - Julian Calendar

    2 or CAL_JEWISH - Jewish Calendar

    3 or CAL_FRENCH - French Revolutionary Calendar

    o If no calendaris specified information on all supported calendars is returned

    as an array.

    SessionHandling:

    A PHP session variable is used to store information about, or change

    settings for a user session. Session variables hold information about onesingle user, and are available to all pages in one application.

    The http protocol that is used widely over the internet is a stateless

    protocol, i.e. it does not remember the state of the user. Example : you

    access your email account using http protocol. When you enter yourcorrect username and pwd, you are taken to your inbox. Now on this page

    if you click on sent mail, this is a second request. But because of statelessnature of http, the server does not remember who this user is. So there

    must be a mechanism that associates multiple requests from a singleuser.

    session_start() : creates a session or resumes the current one based on a

    session identifier passed via a GET or POST request, or passed via a

    cookie.

    o This function returns TRUE if a session was successfully started,

    otherwise FALSE.

    $_SESSION : An associative array containing session variablesavailable to the current script.

    o This is a 'superglobal', or automatic global, variable. Thissimply means that it is available in all scopes throughout ascript.

    Cookies:

  • 7/27/2019 php notes bba 2010-13.doc

    36/41

    A cookie, also known as an HTTP cookie, web cookie, or browser cookie,is used for an origin website to send state information to a user's browser andfor the browser to return the state information to the origin site

    The state information can be used forauthentication, identification of a usersession,

    user's preferences, shopping cart contents, or anything else that can be accomplished

    through storing text data.

    Cookies are not software

    the three major uses of cookies are :

    o session management : Cookies may be used to maintain data related to the user

    during navigation, possibly across multiple visits. the session id can be stored incookies.

    o personalisation : Cookies may be used to remember the information about the user

    who has visited a website in order to show relevant content in the future. Manywebsites use cookies for personalization based on users' preferences. Users selecttheir preferences by entering them in a web form and submitting the form to theserver. The server encodes the preferences in a cookie and sends the cookie backto the browser. This way, every time the user accesses a page, the server is alsosent the cookie where the preferences are stored, and can personalize the pageaccording to the user preferences.

    o tracking : Tracking cookies may be used to track internet users' web browsing

    habits.

    Cookies don't have to be an essential part of a website but can provide some of the "littlethings" that can set your website apart from the rest. Cookies are small tidbits ofinformation that you save on the client's computer so that you can access them next timethey visit the website. Session ID's are also usually held in cookies.

    so a client browser can disable cookies. Also a website may not be using cookies at all.

    So its not compulsory to use cookies but this is very rare.

    to set a cookie :

    o setcookie(name, value, expire, path, domain) : where only name parameter is

    mandatory others are optional

    name : name of cookie

    value : of cookie

    http://en.wikipedia.org/wiki/Authenticationhttp://en.wikipedia.org/wiki/Authenticationhttp://en.wikipedia.org/wiki/Http_sessionhttp://en.wikipedia.org/wiki/Http_sessionhttp://en.wikipedia.org/wiki/Shopping_cart_softwarehttp://en.wikipedia.org/wiki/Authenticationhttp://en.wikipedia.org/wiki/Http_sessionhttp://en.wikipedia.org/wiki/Shopping_cart_software
  • 7/27/2019 php notes bba 2010-13.doc

    37/41

    expire : expiry time in secs. after expiry time this cookie will not beavalaible

    Database handling :

    mysql_connect Open a connection to a MySQL Servero mysql_connect(server,username, password)

    o all are optional parameters

    mysql_select_db Select a MySQL database

    o Sets the current active database on the server that's associated with the

    specified link identifier. Every subsequent call to mysql_query() will bemade on the active database.

    o mysql_select_db (string $database_name) : parameter is the name of the

    databse to be selected.

    o Returns TRUE on success or FALSE on failure.

    mysql_query Send a MySQL query

    o mysql_query ( string $query)

    o mysql_query() sends a unique query (multiple queries are not supported)to the currently active database on the server

    o For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning

    resultset, mysql_query() returns a resource on success, or FALSE on

    error.

    o For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc,

    mysql_query() returns TRUE on success or FALSE on error.

    mysql_result Get result data

    o Retrieves the contents of one cell from a MySQL result set.

    o string mysql_result ( resource $result, int $row [, mixed$field = 0 ] )

    result : The result resource that is being evaluated. This resultcomes from a call to mysql_query().

    row : The row number from the result that's being retrieved. Rownumbers start at 0.

    field : The name or offset of the field being retrieved. It can be thefield's offset, the field's name, or the field's table dot field name

    (tablename.fieldname). If undefined, the first field is retrieved. Ifthe column name has been aliased ('select foo as bar from...'), use

    the alias instead of the column name.

    http://www.php.net/manual/en/language.types.resource.phphttp://www.php.net/manual/en/language.types.resource.phphttp://www.php.net/manual/en/language.types.resource.phphttp://www.php.net/manual/en/language.types.resource.php
  • 7/27/2019 php notes bba 2010-13.doc

    38/41

    Regular Expressions in PHP :

    A regular expression is a pattern of text that consists of ordinary characters (for example,

    letters a through z) and special characters, known as metacharacters. The patterndescribes one or more strings to match when searching a body of text. The regularexpression serves as a template for matching a character pattern to the string beingsearched.

    The following table contains the list of some metacharacters and their behavior in the

    context of regular expressions:

  • 7/27/2019 php notes bba 2010-13.doc

    39/41

    Character Description

    \

    Marks the next character as either a special

    character, a literal, a backreference, or an octalescape. For example, 'n' matches the character

    "n". '\n' matches a newline character. Thesequence '\\' matches "\" and "\(" matches "(".

    ^ Matches the position at the beginning of the input

    string.

    $ Matches the position at the end of the input string.

    * Matches the preceding subexpression zero or

    more times.

    + Matches the preceding subexpression one or more

    times.

    ? Matches the preceding subexpression zero or one

    time.

    {n} Matches exactly n times, where n is a

    nonnegative integer.

    {n,} Matches at least n times, n is a nonnegative

    integer.

    {n,m} Matches at least n and at most m times, where m

    and n are nonnegative integers and n

  • 7/27/2019 php notes bba 2010-13.doc

    40/41

    the specified range.

    [^a-z] A negative range characters. Matches any

    character not in the specified range.

    \b Matches a word boundary, that is, the position

    between a word and a space.

    \B Matches a nonword boundary. 'er\B' matches the

    'er' in "verb" but not the 'er' in "never".

    \d Matches a digit character.

    \D Matches a nondigit character.

    \f Matches a form-feed character.

    \n Matches a newline character.

    \r Matches a carriage return character.

    \s Matches any whitespace character including

    space, tab, form-feed, etc.

    \S Matches any non-whitespace character.

    \t Matches a tab character.

    \v Matches a vertical tab character.

    \w

    Matches any word character including

    underscore.

    \W Matches any nonword character.

    \un

    Matches n, where n is a Unicode character

    expressed as four hexadecimal digits. Forexample, \u00A9 matches the copyright symbol().

    PHP has functions to work on complex string manipulation using RegEx.

    PHP is an open source language for producing dynamic web pages.

    PHP has three sets of functions that allow you to work with regular expressions.

    o The most important set of regex functions start with preg. These functions are a

    PHP wrapper around the PCRE library (Perl-Compatible Regular Expressions).

  • 7/27/2019 php notes bba 2010-13.doc

    41/41

    o The oldest set of regex functions are those that start with ereg. Theyimplement POSIX Extended Regular Expressions, like the traditionalUNIX egrep command.

    o The last set is a variant of the ereg set, prefixing mb_ for "multibyte" tothe function names. While ereg treats the regex and subject string as a

    series of 8-bit characters, mb_ereg can work with multi-byte charactersfrom various code pages

    We are going to see the POSIX extended regex. The following are the RegEx

    functions provided in PHP.

    ereg : Regular expression match.

    o int ereg (string $pattern , string $string [, array &$regs ])

    o Searches a string for matches to the regular expression given in pattern in a

    case-sensitive way.

    ereg_replace :

    o Replace regular expression

    o This function scans string for matches topattern, then replaces thematched text with replacement.

    o string ereg_replace ( string $pattern , string $replacement , string$string )

    $pattern : A POSIX extended regular expression.

    $replacement : Ifpattern contains parenthesized substrings,replacement may contain substrings of the form \\digit, which willbe replaced by the text matching the digit'th parenthesizedsubstring; \\0 will produce the entire contents of string. Up tonine substrings may be used. Parentheses may be nested, inwhich case they are counted by the opening parenthesis.

    $string : The input string.

    The modified string is returned. If no matches are found instring, then it will be returned unchanged.