0% found this document useful (0 votes)
21 views63 pages

Web Based Programming: BCA Semester: II L-7-9

Uploaded by

niftyelbakyan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views63 pages

Web Based Programming: BCA Semester: II L-7-9

Uploaded by

niftyelbakyan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

INSTITUTE OF INFORMATION TECHNOLOGY & MANAGEMENT

Accredited ‘A’ Grade by NAAC &Recognised U/s 2(f) of UGC act


Rated Category `A+’ by SFRC & `A’ by JAC Govt. of NCT of Delhi
Approved by AICTE & Affiliated to GGS Indraprastha University, New Delhi

Web Based Programming


Dr.Ramandeep Kaur
Associate Professor-CS
BCA
Semester: II
L-7-9
Contents:
PHP Language Basics: Arrays, types, functions, multi-dimensional arrays

1 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
PHP Arrays
An array variable is a storage area holding a number or text.
 Array items can be of any data type.
 The most common are strings and numbers (int, float),
 array items can also be objects, functions or even arrays.

The problem is, a variable will hold only one value.


Normal Variable, no key:
$name = ‘Rob’;
An array is a special variable, which can store multiple values in one single
variable.
Array Variable, multiple pieces with ‘keys’:
$name[0] = ‘Rob’;
$name[1] = ‘Si’;
$name[2] = ‘Sarah’;
2 …
© Institute
The ‘key’
of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Array keys
 Array keys can be strings as well as numbers..
$surname[‘rob’] = ‘Tuley’;
$surname[‘si’] = ‘Lewis’;
 Notice the way that the key is specified, in square brackets
following the variable name.

 Array items of four different data type


$myArr = array("Volvo", 15, ["apples", "bananas"], myFunction);

3 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Arrays Types
In PHP, there are three kind of arrays:
> Indexed/Numeric array - An array with a numeric index
> Associative array - An array where each ID key is associated
with a value
> Multidimensional array - An array containing one or more
arrays

4 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Indexed Arrays
 In indexed arrays each item has an index number.
 By default, the first item has index 0, the second item has item 1,
etc.

There are two methods to create a numeric array.

 Create Array (automatic keys):


$letters = array('a','b','c','d');
The array keys are automatically assigned by PHP as 0, 1, 2, 3

 Accessing the Array


$letters[1] has value ‘b’
In the above example the index is automatically assigned
5 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Indexed/ Numeric Arrays
Creation of Manually defined keys and values of array
In the following example you access the variable values by
referring to the array name and index:

Accessing the
The code above will output: Array

6 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Change Value of Array
 To change
 the value of an array item, use the index number:

$cars = array("Volvo", "BMW", "Toyota"); $cars[1] = "Ford";

Iterating Through an Indexed Array


$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as $x)
{
echo "$x <br>";
}

7 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Array_push()
 if you use the array_push() function to add a new item, the new
item will get the index of last element +1
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
array_push($cars, "Ford");
 the new item will get the index 3
 Array with random indexes
 if you have an array with random index numbers, like this
$cars[5] = "Volvo";
$cars[7] = "BMW";
$cars[14] = "Toyota";
array_push($cars, "Ford"); what will be the index number of
the new item?

8 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Associative Arrays
Associative arrays are arrays that use named keys that you assign to
them.
When storing data about specific named values, a numerical array
is not always the best way to do it.
With associative arrays we can use the values as keys and assign
values to them.

 Create Array (explicit keys):


$letters = array(10=>’a’,13=>’b’);
i.e. $letters[13] has value ‘b’

9 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
<?php
$car = array("brand"=>"Ford", "model"=>"Mustang",
"year"=>1964);
var_dump($car); OUTPUT
?>

10 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Creating & Accessing Associative Arrays
 To access an array item you can refer to the key name.

$car = array("brand"=>"Ford", "model"=>"Mustang",


"year"=>1964);
echo $car["model"];

 Change Value
 To change the value of an array item, use the key name:

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);


$car["year"] = 2024;

11 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
PHP Associative Arrays
Alternative way of creating the array:

Loop Through an Associative Array


$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
foreach ($car as $x => $y)
{
echo "$x: $y <br>"; //Display all array items, keys and values:
}

12 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Create, Add, update, Access and Sort
an Array
 Creating an array
i. by using the array() function
$cars = array("Volvo", "BMW", "Toyota");

ii. by using the [] brackets


$cars = ["Volvo", "BMW", "Toyota"];

iii. Multiple Lines $cars = [ "Volvo",


"BMW",
"Toyota" ];

iv. Array Keys Indexed Array Associative Array


$cars = [ 0 => "Volvo", $myCar = ["brand" => "Ford",
1 => "BMW", "model"=> "Mustang",
2 =>"Toyota" "year" => 1964
]; ];
13 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Declare Empty Array
 You can declare an empty array first, and add items to it
later:

Indexed Array Associative Array

$cars = []; $myCar = [];


$cars[0] = "Volvo"; $myCar["brand"] = "Ford";
$cars[1] = "BMW"; $myCar["model"] ="Mustang";
$cars[2] = "Toyota"; $myCar["year"] = 1964;

Mixing Array Keys

$myArr = [];
$myArr[0] = "apples";
$myArr[1] = "bananas";
$myArr["fruit"] = "cherries";

14 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Deleting an Array Element
 Set the array item to an empty string
 This will set the value of a key to empty string but does not
delete the element
$actor[0]=“Cary Grant”;
$actor[1]=“SRK”;
$actor[2]=“Ranvir Singh”;
$actor[0]= “ ”;
 To delete the item in an array, use unset()
unset($actor[0]);
 You will get a warning message that $actor[0] is undefined

15 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Handling arrays with Loops
 The For Loop
$actor[0]="Cary Grant";
$actor[1]="SRK";
$actor[2]="Ranvir Singh";

for($i=0; $i<count($actor); $i++)


{
echo "\$actor[$i] = ", $actor[$i],
"<br>";
}

 Using print_r() for display contents of array without for loop


print_r($actor);

16 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Extracting data from Array
extract($arrayname);

$actor["first"]="Cary Grant";
$actor["second"]="SRK";
$actor["third"]="Ranvir Singh";

extract($actor);

echo "\$first = $first <br>";


echo "\$second = $second <br>";
echo "\$third = $third <br>";

17 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Extracting data from Array
List($key)=$arrayname;
$actor[0]="Cary Grant";
$actor[1]="SRK";
$actor[2]="Ranvir Singh";

list($first, $second)=($actor);

echo "\$first = $first <br>";


echo "\$second = $second <br>";

18 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Sorting Arrays
 Sort function is used to sort arrays in ascending order
<?php
$actor[0]="Cary Grant"; To sort associative array, use asort()
and arsort()
$actor[1]="SRK";
$actor[2]="Ranvir Singh";
echo(" Array before Sorting");
print_r($actor);
echo("<br> Sorted Array");
sort($actor);
print_r($actor);

echo("<br> ReverseSorted Array");


rsort($actor);
print_r($actor);
?>
19 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Multidimensional Arrays
 A multidimensional array is an array containing one or more
arrays.
 PHP supports multidimensional arrays that are two, three, four,
five, or more levels deep.
 However, arrays more than three levels deep are hard to manage
for most people.
 The dimension of an array indicates the number of
indices you need to select an element.
 For a two-dimensional array you need two indices to select an
element
 For a three-dimensional array you need three indices to select an
element

20 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Two-dimensional Arrays(2D)
 A two-dimensional array is an array of arrays
Rows Coloums
Row[0] Col[0] Col[1]
Row[1] Col[0] Col[1]

 Example Cars table can be created as a 2D


COLUMNS array in PHP

$cars = array (
array("Volvo",22,18),
ROWS array("BMW",15,13),
array("Saab",5,2),
array("LandRover",17,15)
);

21 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Ways to create 2D arrays
<?php
 2D $cars array contains
$cars = array (
four arrays, and it has array("Volvo",22,18),
two indices: row and array("BMW",15,13),
column. array("Saab",5,2),
array("Land Rover",17,15)
 To get access to the
);
elements of the $cars echo $cars[0][0].": In stock: ".$cars[0][1].", sold:
array we must point to ".$cars[0][2].".<br>";
the two indices (row echo $cars[1][0].": In stock: ".$cars[1][1].", sold:
and column): ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold:
".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold:
".$cars[3][2].".<br>";
?>
22 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Method-2
<?php
$student["A"] []=70;
$student["A"] [1]=76;
$student["A"] [2]=78;

$student["B"] []=76;
$student["B"] [1]=56;
$student["B"] [2]=86;
Method-3
print_r($student); $student=array(“A” => array(79,70),
echo "A's marks in subject 1 is:", “B” => array(56,70));
$student["A"][1], "\n";
?> © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
23
Dr.Ramandeep Kaur
Looping over multidimensional arrays
<?php
//loops in array
$student[0] []=70;
$student[0] []=76;
$student[0] []=78;

$student[1] []=76;
$student[1] []=56;
$student[1] []=86;
for($outer=0; $outer < count($student); $outer++)
{
for($inner=0; $inner < count($student[$outer]); $inner++)
{
echo "\$student[$outer][$inner] marks is: ", $student[$outer][$inner], "<br>";
} } ?>
24 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
INSTITUTE OF INFORMATION TECHNOLOGY & MANAGEMENT
Accredited ‘A’ Grade by NAAC &Recognised U/s 2(f) of UGC act
Rated Category `A+’ by SFRC & `A’ by JAC Govt. of NCT of Delhi
Approved by AICTE & Affiliated to GGS Indraprastha University, New Delhi

Array Built-in Functions

25 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Comparing Arrays-array_diff()
 Syntax : array_diff(array1, array2);
<?php
$ice_cream=array("Tooti Fruity", "Chocolate", "Mint");
$ice_cream1=array("Tooti Fruity", "Strawberry", "Mint");
$difference=array_diff($ice_cream1,$ice_cream);

foreach($difference as $key => $value)


{
echo "Key: $key; Value : $value <br>";
}
?>

26 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
array_slice()
 creates a slice of an array starting from the specified index
and containing the specified number of elements
 Syntax: array_slice(array, start, length, preserve)
Parameter Description
array Required. Specifies an array
start Required. Numeric value. Specifies where the function will start the slice.
If value =negative number, function will start slicing from last element.
length Optional. Numeric value. Specifies the length of the returned array.

preserve •Optional. Specifies if the function should preserve or reset the keys.
•Possible values:true - Preserve keys
•false - Default. Reset keys

27 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
<?php
$arr=array('ab', 'bc', 'cd', 'de', 'ed', 'fg', 'gh');
$arr1=array_slice($arr, 3, 4);
print_r($arr);
echo '<br>';
print_r($arr1);
echo '<br>';
$arr2=array_slice($arr, 3, 4, true);
print_r($arr);
echo '<br>';
print_r($arr2);
echo '<br>';
?>

28 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
array_splice()
 removes selected elements from an array and replaces it with
new elements.
 The function also returns an array with the removed elements.
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
print_r(array_splice($a1,0,2,$a2));
echo "<br>";
print_r($a1);
?>

29 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
array_intersect()
 The array_intersect() function compares the values of two (or more)
arrays, and returns the matches.
 This function compares the values of two or more arrays, and return
an array that contains the entries from array1 that are present
in array2, array3, etc.
 Syntax : array_intersect(array1, array2, array3, ...)
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");

$result=array_intersect($a1,$a2);
print_r($result);
?>
30 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
array_sum()
 the array_sum() method computes the sum of array elements
<?php
echo 'Original Array...<br>';
$arr1=array(3, 1, 90, -55, 23, 12, 80);
$sum=array_sum($arr1);
print_r($arr1);
echo '<br>Sum of elements: '.$sum;
?>

31 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
array_product()
 the array_product() method computes the product of array
elements
<?php
echo 'Original Array...<br>';
$arr1=array(3, 6, -2, -5, 2, 7, 15);
$product=array_product($arr1);
print_r($arr1);
echo '<br>Product of elements: '.$product;
?>

32 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
array_reverse()
<?php
echo 'Original Array...<br>';
$arr1=array(3, 6, -2, -5, 2, 7, 15);
$arr2=array_reverse($arr1);
print_r($arr1);
echo '<br>Reversed Array...<br> ';
print_r($arr2);
?>

33 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
ksort() and krsort()
 the ksort() function sorts the keys of an associative array in
ascending order.
 While the krsort() function sorts the keys in descending order.
<?php
echo 'Original Array...<br>';
$arr1=array('d'=>3, 'j'=>6, 'a'=>-2, 'p'=>-5, 'x'=>2, 'm'=>7,
'e'=>15);
print_r($arr1);
echo '<br>Sorting an associative array in ascending order of
keys...<br> ';
ksort($arr1);
print_r($arr1);
echo '<br>';
echo '<br>Sorting an associative array in descending order of
keys...<br> ';
krsort($arr1);
print_r($arr1);
?> © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
34
Dr.Ramandeep Kaur
array_keys()
 this function fetches the keys from an associative array
<?php
echo 'Original Array...<br>';
$arr1=array('d'=>3, 'j'=>6, 'a'=>-2, 'p'=>-5, 'x'=>2, 'm'=>7, 'e'=>15);
print_r($arr1);
echo '<br><br>';
echo 'All Keys of the array....<br>';
$keys=array_keys($arr1);
print_r($keys);
?>

35 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
array_values()
 to retrieve the values in an associative array, we can use the
array_values() function
<?php
echo 'Original Array...<br>';
$arr1=array('d'=>3, 'j'=>6,
'a'=>-2, 'p'=>-5, 'x'=>2,
'm'=>7, 'e'=>15);
print_r($arr1);
echo '<br><br>';
echo 'All Values of the
array....<br>';
$values=array_values($arr1);
print_r($values);
?>

36 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
array_pad()
 inserts a specified number of elements, with a specified
value, to an array.
 Syntax : array_pad(array, size, value)

Parameter Description

array Required. Specifies an array

size Required. Specifies the number of elements in the array returned from
the function
value Required. Specifies the value of the new elements in the array returned
from the function

37 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Examples
1.
<?php
$a=array("red","green");
print_r(array_pad($a,5,"blue"));
?>

2.
<?php
$a=array("red","green");
print_r(array_pad($a,-5,"blue"));
?>

38 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
compact()
 The compact() function creates an array from variables and
their values.
 Syntax :compact(var1, var2...)
<?php
$firstname = "Peter";
$lastname = "Griffin";
$age = "41";

$result = compact("firstname", "lastname", "age");

print_r($result);
?>

39 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
current()
 returns the value of the current element in an array.
 Every array has an internal pointer to its "current" element,
which is initialized to the first element inserted into the
array.
•Related Functions to traverse in an array
•end() - moves the internal pointer to, and outputs, the last element in the array
•next() - moves the internal pointer to, and outputs, the next element in the array
•prev() - moves the internal pointer to, and outputs, the previous element in the array
•reset() - moves the internal pointer to the first element of the array
•each() - returns the current element key and value, and moves the internal pointer forward

40 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Example
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");

echo current($people) . "<br>"; // The current element is Peter


echo next($people) . "<br>"; // The next element of Peter is Joe
echo current($people) . "<br>"; // Now the current element is Joe
echo prev($people) . "<br>"; // The previous element of Joe is Peter
echo end($people) . "<br>"; // The last element is Cleveland
echo prev($people) . "<br>"; // The previous element of Cleveland is Glenn
echo current($people) . "<br>"; // Now the current element is Glenn
echo reset($people) . "<br>"; // Moves the internal pointer to the first element of the
array, echo next($people) . "<br>" . "<br>"; // The next element of Peter is Joe
print_r (each($people));

41 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Output

42 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Date()

• date() function formats a local date and time, and returns the formatted date string.
• Syntax: date(format, timestamp)

date() Formats a local date and time


getdate() Returns date/time information of a timestamp or the current local date/time

d - The day of the month (from 01 to 31)


D - A textual representation of a day (three letters)
j - The day of the month without leading zeros (1 to 31)
S - The English ordinal suffix for the day of the month (2 characters st, nd, rd or th.Works
well with j)
w - A numeric representation of the day (0 for Sunday, 6 for Saturday)
z - The day of the year (from 0 through 365)

43 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
<?php
// Prints the day
echo date("l") . "<br>";
echo date("D") . "<br>";
echo date("w") . "<br>";
// Prints the day, date, month, year, time, AM or PM
echo date("l jS \of F Y h:i:s A") . "<br>";
echo("<br>");
print_r(getdate());
echo("<br>");
echo gettimeofday(true);
?>

44 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Regular Expressions
 A regular expression is a sequence of characters that forms a
search pattern. When you search for data in a text, you can
use this search pattern to describe what you are searching
for.
 A regular expression can be a single character, or a more
complicated pattern.
 Regular expressions can be used to perform all types of text
search and text replace operations.
 Syntax: $exp = "/w3schools/i";
/ is the delimiter, w3schools is the pattern that is being searched for,
i is a modifier that makes the search case-insensitive.

45 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Regular Expression Functions
Function Description
preg_match() Returns 1 if the pattern was found in the string and 0 if not
preg_match_all() Returns the number of times the pattern was found in the string, which may also
be 0
preg_replace() Returns a new string where matched patterns have been replaced with another
string

preg_match() preg_match_all()
<?php <?php
$str = "Visit W3Schools"; $str = "The rain in SPAIN falls mainly on plains.";
$pattern = "/w3schools/i"; $pattern = "/ain/i";
echo preg_match($pattern, $str); echo preg_match_all($pattern, $str);
?> ?>
//OUTPUT-1 //OUTPUT- 4
46 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
preg_replace()
 replace all of the matches of the pattern in a string with
another string.

<?php
$str = "The rain in SPAIN falls mainly on the plains";
$pattern = "/ain/i";
echo preg_replace($pattern, "CHANGED", $str);
?>

47 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Regular Expression Modifiers
Modifier Description
i Performs a case-insensitive search

m Performs a multiline search (patterns that search for a match at the


beginning or end of a string will now match the beginning or end
of each line)
u Enables correct matching of UTF-8 encoded patterns

48 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Regular Expression Patterns
 Brackets are used to find a range of characters:
Expression Description
[abc] Find one or many of the characters inside the brackets
[^abc] Find any character NOT between the brackets
[a-z] Find any character alphabetically between two letters
[A-z] Find any character alphabetically between a specified upper-
case letter and a specified lower-case letter
[A-Z] Find any character alphabetically between two upper-case
letters.
[123] Find one or many of the digits inside the brackets
[0-5] Find any digits between the two numbers
[0-9] Find any digits
49 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Metacharacters
Metacharacter Description
| Find a match for any one of the patterns separated by | as in: cat|dog|fish
. Find any character
^ Finds a match as the beginning of a string as in: ^Hello
$ Finds a match at the end of the string as in: World$
\d Find any digits
\D Find any non-digits
\s Find any whitespace character
\S Find any non-whitespace character
\w Find any alphabetical letter (a to Z) and digit (0 to 9)
\W Find any non-alphabetical and non-digit character
\b Find a match at the beginning of a word like this: \bWORD, or at the end of a word
like this: WORD\b
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx
50 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Quantifiers
Quantifier Description
n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more occurrences of n


n? Matches any string that contains zero or one occurrences of n
n{3} Matches any string that contains a sequence of 3 n's

n{2, 5} Matches any string that contains a sequence of at least 2, but not
more that 5 n's
n{3,} Matches any string that contains a sequence of at least 3 n's

51 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
1. [abc] expression
<?php
$txt = "W3Schools.com";
$pattern = "/[co]/";
echo preg_match_all($pattern, $txt);
Echo “The matches were found here:”;
echo preg_replace($pattern, "#", $txt);
?>

2. [^abc] expression
<?php
$txt = "Welcome";
$pattern = "/[^eo]/";
echo preg_match_all($pattern, $txt); OUTPUT:4
?>

52 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
3.Upper and Lower case
<?php
echo "How many letters in the text are alphabetically between e and o:";
$txt = "Welcome to Web Based Programming";
$pattern = "/[e-o]/";
$pattern1= "/[A-F]/i";
echo preg_match_all($pattern, $txt);
echo"<br>";
echo "How many letters in the text are alphabetically between A and F:";
echo preg_match_all($pattern1, $txt);
?>

53 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
4. ‘|’ modifier(OR), &, ^
<?php
echo "To identify the occurrences of animal: ";
$txt = "We have three dogs, one fish, but no cats";
$pattern = "/cat|dog|fish/";
echo preg_match_all($pattern, $txt);
echo "<br>";
echo "to identify a string at the start of the sentence: ";
$pattern1 = "/^We/";
echo preg_match_all($pattern1, $txt);
echo "<br>to identify a string at the end of the sentence: ";
$pattern2 = "/al$/";
echo preg_match_all($pattern2, $txt);
?>

54 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
5. Occurrence of string at beginning /
end of a word
<?php
$txt = "Hello HelloWorld World";
$pattern = "/\bHel/";
$pattern1="/rld\b/";
echo "To check for a string at beginning or end of a word <br>";
echo "At the beginning",preg_match_all($pattern, $txt),"<br>";
echo "At the end", preg_match_all($pattern1, $txt),"<br>";
?>

55 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
6. n+ modifier for min ‘n’ occurrences

<?php
echo "+ modifiers";
$txt = "Web Based Programming in BCA second semester";
$pattern = "/s+/";
echo "<br>";
echo "number of occurrences of \'s\': ";
echo preg_match_all($pattern, $txt);
?>

56 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
7. {m,n}occurrences
<?php
$txt = "Web Based Programming is gooood";
echo "text to be checked: ",$txt;
$pattern = "/o{2,5}/";
echo preg_match_all($pattern, $txt);
?>

57 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Grouping using ()
 You can use parentheses ( ) to apply quantifiers to entire
patterns.
 They also can be used to select parts of the pattern to be
used as a match.
<?php
$str = "Apples and bananas and more bananas.";
$pattern = "/ba(na){2}/i";
echo preg_match_all($pattern, $str);
?>

OUTPUT: 2

58 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Anonymous Functions
 those functions that we create without a name
 suppose we need to pass a function as a parameter to another
function , create an anonymous function and assign it to a
variable. Then, we can pass this variable as a parameter.
<?php
$v=function($x, $y){ return
$x+$y;};
echo $v(3, 4);
?>

59 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
compute the sum of integers from 1 to
the value of a specific array element.

<?php
$arr=array(1,2,3,4,5,6,7,8,9,10);
array_walk($arr, function($n){
$s=0;
for($i=1;$i<=$n;$i++){
$s+=$i;
}
echo 'Number: ',$n,' Sum: ',$s,'<br>';});
?>

60 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Difference between print and echo
echo print
1. It has no return value 1. It has a return value of 1 so it
2. It can take multiple parameters can be used in expressions
3. echo is marginally faster than print 2. It can take one argument
4. Examples 3. print is marginally slower than
1. echo "<h2>PHP is Fun!</h2>"; echo
2. echo "Hello world!<br>"; 4. Examples
3. echo "I'm about to learn
PHP!<br>";
1. print "<h2>PHP is
Fun!</h2>";
4. echo "This ", "string ", "was ",
"made ", "with multiple 2. print "Hello world!<br>";
parameters."; 3. print "I'm about to learn PHP!";

61 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
Difference between ‘’ and “”
 single-quoted strings are plain text with virtually no special
case whereas double-quoted strings have variable
interpolation (e.g. echo "Hello $username";) as well as
escaped sequences such as "\n" (newline.)
With single quotes : With Double quotes :

• variables and escape sequences for • The most important feature of double-
special characters will not be expanded quoted strings is the fact that variable
For instance : names will be expanded.
• echo 'Variables do not $expand $either'; For instance :
• output : Variables do not $expand $a = 10;
$either echo "a is $a";
output : a is 10
62 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur
=, == and === in PHP
 The assignment equality = operator only assigns values.
 The equality == does not assign values, but compares them
without checking their data types.
 The triple equals sign operator === won't do assignment,
but will check for equality of values and the data type.

63 © Institute of Information Technology and Management, D-29, Institutional Area, Janakpuri, New Delhi-110058
Dr.Ramandeep Kaur

You might also like