Unit 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

What is PHP?

• PHP is an acronym for "PHP: Hypertext Preprocessor"


• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP is free to download and use

PHP is an amazing and popular language!

It is powerful enough to be at the core of the biggest blogging system on the


web (WordPress)!
It is deep enough to run large social networks!
It is also easy enough to be a beginner's first server side language!

What is a PHP File?


• PHP files can contain text, HTML, CSS, JavaScript, and PHP code
• PHP code is executed on the server, and the result is returned to the
browser as plain HTML
• PHP files have extension ".php"

What Can PHP Do?


• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and close files on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data

With PHP you are not limited to output HTML. You can output images, PDF
files, and even Flash movies. You can also output any text, such as XHTML
and XML.

PHP Syntax
A PHP script is executed on the server, and the plain HTML result is sent
back to the browser.

Basic PHP Syntax


A PHP script can be placed anywhere in the document.

A PHP script starts with <?php and ends with ?>:

<?php
// PHP code goes here
?>

The default file extension for PHP files is ".php".

A PHP file normally contains HTML tags, and some PHP scripting code.

Below, we have an example of a simple PHP file, with a PHP script that uses
a built-in PHP function "echo" to output the text "Hello World!" on a web
page:

Example
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>

Note: PHP statements end with a semicolon (;).

PHP Case Sensitivity


In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and
user-defined functions are not case-sensitive.

In the example below, all three echo statements below are equal and legal:

Example
<!DOCTYPE html>
<html>
<body>

<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>

</body>
</html>

Note: However; all variable names are case-sensitive!

Look at the example below; only the first statement will display the value of
the $color variable! This is because $color, $COLOR, and $coLOR are treated
as three different variables:

Example
<!DOCTYPE html>
<html>
<body>

<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>

</body>
</html>

Comments in PHP
A comment in PHP code is a line that is not executed as a part of the
program. Its only purpose is to be read by someone who is looking at the
code.

Comments can be used to:

• Let others understand your code


• Remind yourself of what you did - Most programmers have
experienced coming back to their own work a year or two later and
having to re-figure out what they did. Comments can remind you of
what you were thinking when you wrote the code

PHP supports several ways of commenting:


Example
Syntax for single-line comments:

<!DOCTYPE html>
<html>
<body>

<?php
// This is a single-line comment

# This is also a single-line comment


?>

</body>
</html>

Example
Syntax for multiple-line comments:

<!DOCTYPE html>
<html>
<body>

<?php
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>

</body>
</html>

Example
Using comments to leave out parts of the code:

<!DOCTYPE html>
<html>
<body>

<?php
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>

</body>
</html>

Creating (Declaring) PHP Variables


In PHP, a variable starts with the $ sign, followed by the name of the
variable:

Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>

After the execution of the statements above, the variable $txt will hold the
value Hello world!, the variable $x will hold the value 5, and the
variable $y will hold the value 10.5.

Note: When you assign a text value to a variable, put quotes around the
value.

Note: Unlike other programming languages, PHP has no command for


declaring a variable. It is created the moment you first assign a value to it.

Think of variables as containers for storing data.

PHP Variables
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume).

Rules for PHP variables:


• A variable starts with the $ sign, followed by the name of the variable
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive ($age and $AGE are two different
variables)

Remember that PHP variable names are case-sensitive!

Output Variables
The PHP echo statement is often used to output data to the screen.

The following example will show how to output text and a variable:

Example
<?php
$txt = "ShillongCollege.com";
echo "I love $txt!";
?>

PHP is a Loosely Typed Language


In the example above, notice that we did not have to tell PHP which data
type the variable is.

PHP automatically associates a data type to the variable, depending on its


value. Since the data types are not set in a strict sense, you can do things
like adding a string to an integer without causing an error.

In PHP 7, type declarations were added. This gives an option to specify the
data type expected when declaring a function, and by enabling the strict
requirement, it will throw a "Fatal Error" on a type mismatch.

You will learn more about strict and non-strict requirements, and data type
declarations in the PHP Functions chapter.
PHP Functions
The real power of PHP comes from its functions.

PHP has more than 1000 built-in functions, and in addition you can create
your own custom functions.

PHP Built-in Functions


PHP has over 1000 built-in functions that can be called directly, from within a
script, to perform a specific task.

Please check out our PHP reference for a complete overview of the PHP built-
in functions.

PHP User Defined Functions


Besides the built-in PHP functions, it is possible to create your own functions.

• A function is a block of statements that can be used repeatedly in a


program.
• A function will not execute automatically when a page loads.
• A function will be executed by a call to the function.

Create a User Defined Function in PHP


A user-defined function declaration starts with the word function:

Syntax
function functionName() {
code to be executed;
}
Note: A function name must start with a letter or an underscore. Function
names are NOT case-sensitive.

Tip: Give the function a name that reflects what the function does!

In the example below, we create a function named "writeMsg()". The opening


curly brace ( { ) indicates the beginning of the function code, and the closing
curly brace ( } ) indicates the end of the function. The function outputs "Hello
world!". To call the function, just write its name followed by brackets ():

Example
<?php
function writeMsg() {
echo "Hello world!";
}

writeMsg(); // call the function


?>

PHP Function Arguments


Information can be passed to functions through arguments. An argument is
just like a variable.

Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument ($fname). When the
familyName() function is called, we also pass along a name (e.g. Jani), and
the name is used inside the function, which outputs several different first
names, but an equal last name:

Example
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}

familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>

The following example has a function with two arguments ($fname and
$year):

Example
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}

familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>

PHP is a Loosely Typed Language


In the example above, notice that we did not have to tell PHP which data
type the variable is.

PHP automatically associates a data type to the variable, depending on its


value. Since the data types are not set in a strict sense, you can do things
like adding a string to an integer without causing an error.

In PHP 7, type declarations were added. This gives us an option to specify


the expected data type when declaring a function, and by adding
the strict declaration, it will throw a "Fatal Error" if the data type
mismatches.

In the following example we try to send both a number and a string to the
function without using strict:

Example
<?php
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is NOT enabled "5 days" is changed to int(5), and it
will return 10
?>
To specify strict we need to set declare(strict_types=1);. This must be on the
very first line of the PHP file.

In the following example we try to send both a number and a string to the
function, but here we have added the strict declaration:

Example
<?php declare(strict_types=1); // strict requirement

function addNumbers(int $a, int $b) {


return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is enabled and "5 days" is not an integer, an error
will be thrown
?>

The strict declaration forces things to be used in the intended way.

PHP Default Argument Value


The following example shows how to use a default parameter. If we call the
function setHeight() without arguments it takes the default value as
argument:

Example
<?php declare(strict_types=1); // strict requirement
function setHeight(int $minheight = 50) {
echo "The height is : $minheight <br>";
}

setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>

PHP Functions - Returning values


To let a function return a value, use the return statement:

Example
<?php declare(strict_types=1); // strict requirement
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}

echo "5 + 10 = " . sum(5, 10) . "<br>";


echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>

PHP Return Type Declarations


PHP 7 also supports Type Declarations for the return statement. Like with the
type declaration for function arguments, by enabling the strict requirement,
it will throw a "Fatal Error" on a type mismatch.

To declare a type for the function return, add a colon ( : ) and the type right
before the opening curly ( { )bracket when declaring the function.

In the following example we specify the return type for the function:

Example
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : float {
return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>

You can specify a different return type, than the argument types, but make
sure the return is the correct type:

Example
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : int {
return (int)($a + $b);
}
echo addNumbers(1.2, 5.2);
?>

Passing Arguments by Reference


In PHP, arguments are usually passed by value, which means that a copy of
the value is used in the function and the variable that was passed into the
function cannot be changed.

When a function argument is passed by reference, changes to the argument


also change the variable that was passed in. To turn a function argument
into a reference, the & operator is used:

Example
Use a pass-by-reference argument to update a variable:

<?php
function add_five(&$value) {
$value += 5;
}

$num = 2;
add_five($num);
echo $num;
?>

PHP Constants
Constants are like variables except that once they are defined they cannot
be changed or undefined.

PHP Constants
A constant is an identifier (name) for a simple value. The value cannot be
changed during the script.

A valid constant name starts with a letter or underscore (no $ sign before the
constant name).
Note: Unlike variables, constants are automatically global across the entire
script.

Create a PHP Constant


To create a constant, use the define() function.

Syntax
define(name, value, case-insensitive)

Parameters:

• name: Specifies the name of the constant


• value: Specifies the value of the constant
• case-insensitive: Specifies whether the constant name should be case-
insensitive. Default is false

Example
Create a constant with a case-sensitive name:

<?php
define("GREETING", "Welcome to ShillongCollege.com!");
echo GREETING;
?>

PHP Conditional Statements


Very often when you write code, you want to perform different actions for
different conditions. You can use conditional statements in your code to do
this.

In PHP we have the following conditional statements:

• if statement - executes some code if one condition is true


• if...else statement - executes some code if a condition is true and
another code if that condition is false
• if...elseif...else statement - executes different codes for more
than two conditions
• switch statement - selects one of many blocks of code to be executed
PHP - The if Statement
The if statement executes some code if one condition is true.

Syntax
if (condition) {
code to be executed if condition is true;
}

Example
Output "Have a good day!" if the current time (HOUR) is less than 20:

<?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
}
?>

PHP - The if...else Statement


The if...else statement executes some code if a condition is true and
another code if that condition is false.

Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}

Example
Output "Have a good day!" if the current time is less than 20, and "Have a
good night!" otherwise:

<?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

PHP - The if...elseif...else Statement


The if...elseif...else statement executes different codes for more than
two conditions.

Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is
true;
} else {
code to be executed if all conditions are false;
}

Example
Output "Have a good morning!" if the current time is less than 10, and "Have
a good day!" if the current time is less than 20. Otherwise it will output
"Have a good night!":

<?php
$t = date("H");

if ($t < "10") {


echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

The PHP switch Statement


Use the switch statement to select one of many blocks of code to be
executed.

Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}

This is how it works: First we have a single expression n (most often a


variable), that is evaluated once. The value of the expression is then
compared with the values for each case in the structure. If there is a match,
the block of code associated with that case is executed. Use break to prevent
the code from running into the next case automatically.
The default statement is used if no match is found.

Example
<?php
$favcolor = "red";

switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
The PHP while Loop
The while loop executes a block of code as long as the specified condition is
true.

Syntax
while (condition is true) {
code to be executed;
}

Examples
The example below displays the numbers from 1 to 5:

Example
<?php
$x = 1;

while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>

The PHP do...while Loop


The do...while loop will always execute the block of code once, it will then
check the condition, and repeat the loop while the specified condition is true.

Syntax
do {
code to be executed;
} while (condition is true);

Examples
The example below first sets a variable $x to 1 ($x = 1). Then, the do while
loop will write some output, and then increment the variable $x with 1. Then
the condition is checked (is $x less than, or equal to 5?), and the loop will
continue to run as long as $x is less than, or equal to 5:
Example
<?php
$x = 1;

do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>

The PHP for Loop


The for loop is used when you know in advance how many times the script
should run.

Syntax
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}

Parameters:

• init counter: Initialize the loop counter value


• test counter: Evaluated for each loop iteration. If it evaluates to TRUE,
the loop continues. If it evaluates to FALSE, the loop ends.
• increment counter: Increases the loop counter value

Examples
The example below displays the numbers from 0 to 10:

Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>

The PHP foreach Loop


The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array.

Syntax
foreach ($array as $value) {
code to be executed;
}

For every loop iteration, the value of the current array element is assigned to
$value and the array pointer is moved by one, until it reaches the last array
element.

Examples
The following example will output the values of the given array ($colors):

Example
<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {


echo "$value <br>";
}
?>

The following example will output both the keys and the values of the given
array ($age):

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $val) {


echo "$x = $val<br>";
}
?>

What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars
in single variables could look like this:

$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";

However, what if you want to loop through the cars and find a specific one?
And what if you had not 3 cars, but 300?

The solution is to create an array!

An array can hold many values under a single name, and you can access the
values by referring to an index number.

Create an Array in PHP


In PHP, the array() function is used to create an array:

array();

In PHP, there are three types of arrays:

• Indexed arrays - Arrays with a numeric index


• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays

PHP Indexed Arrays


There are two ways to create indexed arrays:

The index can be assigned automatically (index always starts at 0), like this:

$cars = array("Volvo", "BMW", "Toyota");

or the index can be assigned manually:

$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";

The following example creates an indexed array named $cars, assigns three
elements to it, and then prints a text containing the array values:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

Loop Through an Indexed Array


To loop through and print all the values of an indexed array, you could use
a for loop, like this:

Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {


echo $cars[$x];
echo "<br>";
}
?>

PHP Associative Arrays


Associative arrays are arrays that use named keys that you assign to them.

There are two ways to create an associative array:

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

or:

$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";

The named keys can then be used in a script:


Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

Loop Through an Associative Array


To loop through and print all the values of an associative array, you could
use a foreach loop, like this:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

PHP - 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

PHP - Two-dimensional Arrays


A two-dimensional array is an array of arrays (a three-dimensional array is
an array of arrays of arrays).

First, take a look at the following table:

Name Stock So

Volvo 22 18

BMW 15 13

Saab 5 2

Land Rover 17 15

We can store the data from the table above in a two-dimensional array, like
this:

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

Now the two-dimensional $cars array contains four arrays, and it has two
indices: row and column.

To get access to the elements of the $cars array we must point to the two
indices (row and column):

Example
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold:
".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold:
".$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>";
?>

PHP Strings
A string is a sequence of characters, like "Hello world!".

PHP String Functions


In this chapter we will look at some commonly used functions to manipulate
strings.

strlen() - Return the Length of a String


The PHP strlen() function returns the length of a string.

Example
Return the length of the string "Hello world!":

<?php
echo strlen("Hello world!"); // outputs 12
?>

str_word_count() - Count Words in a


String
The PHP str_word_count() function counts the number of words in a string.

Example
Count the number of word in the string "Hello world!":

<?php
echo str_word_count("Hello world!"); // outputs 2
?>

strrev() - Reverse a String


The PHP strrev() function reverses a string.

Example
Reverse the string "Hello world!":

<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>

strpos() - Search For a Text Within a String


The PHP strpos() function searches for a specific text within a string. If a
match is found, the function returns the character position of the first match.
If no match is found, it will return FALSE.

Example
Search for the text "world" in the string "Hello world!":

<?php
echo strpos("Hello world!", "world"); // outputs 6
?>

Tip: The first character position in a string is 0 (not 1).


str_replace() - Replace Text Within a String
The PHP str_replace() function replaces some characters with some other
characters in a string.

Example
Replace the text "world" with "Dolly":

<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello
Dolly!
?>

PHP | Regular Expressions

What is a Regular Expression?


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
In PHP, regular expressions are strings composed of delimiters, a pattern and optional
modifiers.
$exp = "/shillong/i";

Regular expressions commonly known as a regex (regexes) are a sequence of characters


describing a special search pattern in the form of text string. They are basically used in
programming world algorithms for matching some loosely defined patterns to achieve some
relevant tasks. Some times regexes are understood as a mini programming language with a
pattern notation which allows the users to parse text strings. The exact sequence of characters
are unpredictable beforehand, so the regex helps in fetching the required strings based on a
pattern definition.
Advantages and uses of Regular expressions:
In many scenarios, developers face problems whenever data are collected in free text fields as
most of the programming deals with data entries. Regular expressions are used almost
everywhere in today’s application programming.
• Regular expressions help in validation of text strings which are of programmer’s
interest.
• It offers a powerful tool for analyzing, searching a pattern and modifying the text data.
• It helps in searching specific string pattern and extracting matching results in a
flexible manner.
• It helps in parsing text files looking for a defined sequence of characters for further
analysis or data manipulation.
• With the help of in-built regexes functions, easy and simple solutions are provided for
identifying patterns.
• It effectively saves a lot of development time, which are in search of specific string
pattern.
• It helps in important user information validations like email address, phone numbers
and IP address.
• It helps in highlighting special keywords in a file based on search result or input.
• It helps in identifying specific template tags and replacing those data with the actual
data as per the requirement.
• Regexes are very useful for creation of HTML template system recognizing tags.
• Regexes are mostly used for browser detection, spam filtration, checking password
strength and form validations.
The following table shows some regular expressions and the corresponding string which
matches the regular expression pattern.
Regular Expression Matches
geeks The string “geeks”
^geeks The string which starts with “geeks”
geeks$ The string which have “geeks” at the end.
^geeks$ The string where “geeks” is alone on a string.
[abc] a, b, or c
[a-z] Any lowercase letter
[^A-Z] Any letter which is NOT a uppercase letter
(gif|png) Either “gif” or “png”
[a-z]+ One or more lowercase letters
^[a-zA-Z0-9]{1, }$ Any word with at least one number or one letter
([ax])([by]) ab, ay, xb, xy
[^A-Za-z0-9] Any symbol other than a letter or other than number
([A-Z]{3}|[0-9]{5}) Matches three letters or five numbers
Note: Complex search patterns can be created by applying some basic regular expression
rules. Even many arithmetic operators like +, ^, – are used by regular expressions for creating
little complex patterns.
Operators in Regular Expression: Let us look into some of the operators in PHP regular
expressions.

Operator Description
^ It denotes the start of string.
$ It denotes the end of string.
. It denotes almost any single character.
() It denotes a group of expressions.
[] It finds a range of characters for example [xyz] means x, y or z .
[^] It finds the items which are not in range for example [^abc] means NOT a, b or c.
It finds for character range within the given item range for example [a-z] means a
– (dash)
through z.
| (pipe) It is the logical OR for example x | y means x OR y.
? It denotes zero or one of preceding character or item range.
* It denotes zero or more of preceding character or item range.
+ It denotes one or more of preceding character or item range.
{n} It denotes exactly n times of preceding character or item range for example n{2}.
{n, } It denotes atleast n times of preceding character or item range for example n{2, }.
{n, m} It denotes atleast n but not more than m times for example n{2, 4} means 2 to 4 of n.
\ It denotes the escape character.

Special Character Classes in Regular Expressions: Let us look into some of the special
characters used in regular expressions.
Special Character Meaning
\n It denotes a new line.
\r It denotes a carriage return.
\t It denotes a tab.
\v It denotes a vertical tab.
\f It denotes a form feed.
\xxx It denotes octal character xxx.
\xhh It denotes hex character hh.
Predefined functions or Regex library: Let us look into the quick cheat sheet of pre-defined
functions for regular expressions in PHP. PHP provides the programmers to many useful
functions to work with regular expressions.
The below listed in-built functions are case-sensitive.

Function Definition
This function searches for a specific pattern against some string. It returns true if
preg_match()
pattern exists and false otherwise.
preg_match_a This function searches for all the occurrences of string pattern against the string.
ll() This function is very useful for search and replace.
This function searches for specific string pattern and replace the original string with
ereg_replace()
the replacement string, if found.
eregi_replace( The function behaves like ereg_replace() provided the search for pattern is not case
) sensitive.
This function behaves like ereg_replace() function provided the regular expressions
preg_replace()
can be used in the pattern and replacement strings.
The function behaves like the PHP split() function. It splits the string by regular
preg_split()
expressions as its parameters.
This function searches all elements which matches the regular expression pattern
preg_grep()
and returns the output array.
This function takes string and quotes in front of every character which matches the
preg_quote()
regular expression.
This function searches for a string which is specified by a pattern and returns true if
ereg()
found, otherwise returns false.
eregi() This function behaves like ereg() function provided the search is not case sensitive.

Using preg_match()
The preg_match() function will tell you whether a string contains matches of a pattern.

Example
Use a regular expression to do a case-insensitive search for "ShillongCollege" in a string:
<?php
$str = "Visit schools123";
$pattern = "/schools/";
$result=preg_match($pattern, $str); // Outputs 1
echo $result;
?>
Using preg_match_all()
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str); // Outputs 4
?>

Using preg_replace()
The preg_replace() function will replace all of the matches of the pattern in a string
with another string.
Example
Use a case-insensitive regular expression to replace Microsoft with ShillongCollege in a
string:
<?php
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "School", $str); // Outputs "Visit Schools!"
?>

Example

<?php

// Declare a regular expression

$regex = '/^[a-zA-Z ]*$/';


// Declare a string

$nameString = 'Sharukh khan';

// Use preg_match() function to

// search string pattern

if(preg_match($regex, $nameString)) {

echo("Name string matching with"

. " regular expression");

else {

echo("Only letters and white space"

. " allowed in name string");

?>

Output:
Name string matching with regular expression

POSIX Regular Expressions: Some regular expressions in PHP are like arithmetic
expressions which are called POSIX regular expressions. Some times, complex expression
are created by combining various elements or operators in regular expressions. The very basic
regex is the one which matches a single character.
Lets look into some of the POSIX regular expressions.

Regex Meaning
[0-9] It matches digit from 0 through 9.
[a-z] It matches any lowercase letter from a through z.
[A-Z] It matches any uppercase letter from A through Z.
[a-Z] It matches any lowercase letter a through uppercase letter Z.

Quantifiers in Regular Expression: Quantifiers are special characters which tell the
quantity, frequency or the number of instances or occurrence of bracketed character or group
of characters. They are also called as greedy and lazy expressions. Let us look into some of
the concepts and examples of quantifiers.

Quantifier Meaning
a+ It matches the string containing at least one a.
a* It matches the string containing zero or more a’s.
a? It matches any string containing zero or one a’s.
a{x} It matches letter ‘a’ exaclty x times .
a{2, 3} It matches any string containing the occurrence of two or three a’s.
a{2, } It matches any string containing the occurrence of at least two a’s.
a{2} It matches any string containing the occurrence of exactly two a’s.
a{, y} It matches any string containing the occurrence of not more than y number of a’s.
a$ It matches any string with ‘a’ at the end of it.
^a It matches any string with ‘a’ at the beginning of it.
[^a-zA-Z] It matches any string pattern not having characters from a to z and A to Z.
a.a It matches any string pattern containing a, then any character and then another a.
^.{3}$ It matches any string having exactly three characters.

PHP - Validate Name


The code below shows a simple way to check if the name field only contains letters, dashes,
apostrophes and whitespaces. If the value of the name field is not valid, then store an error
message:
$name = “Peter3”;
$pattern="/^[a-zA-Z]*$/";
if (!preg_match($pattern,$name)) {
echo( "Only letters and white space allowed");
else
echo (“Correct and accepted....”);
}

PHP - Validate E-mail


The easiest and safest way to check whether an email address is well-formed is to use PHP's
filter_var() function.
In the code below, if the e-mail address is not well-formed, then store an error message:
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}

or

(!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-
z]{2,6}$/ix", $str))

PHP - Validate URL


The code below shows a way to check if a URL address syntax is valid (this regular
expression also allows dashes in the URL). If the URL address syntax is not valid, then store
an error message:
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}

• Create a regular expression pattern that matches any valid email address.
"^[a-zA-Z._]+@[a-zA-Z]+(\\.[a-zA-Z]+)+$"

• Any car registration number in the form ML01 A 1023 or ML04 1234. [ML0# (A-Z)
####] – The pattern should match string that start with ML0 followed by any digit
from 1-9, a space, any alphabet A-Z and a space (which is optional) and four digit
numbers.
"^ML[1-9]{2} +([A-Z] )?[0-9]{4}$"
"^[A-Z]{2}[1-9]{2} ([A-Z] )?[0-9]{4}$"

• A string in the form BCA15alex12.


• [BCA##$$$$##] – “^BCA[0-9]{2}[a-z]{4}[0-9]{2}$”
PHP Data Types
Variables can store data of different types, and different data types can do
different things.

PHP supports the following data types:

• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource

PHP String
A string is a sequence of characters, like "Hello world!".

A string can be any text inside quotes. You can use single or double quotes:

Example
<?php
$x = "Hello world!";
$y = 'Hello world!';

echo $x;
echo "<br>";
echo $y;
?>

PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647.
Rules for integers:

• An integer must have at least one digit


• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in: decimal (base 10), hexadecimal (base
16), octal (base 8), or binary (base 2) notation

In the following example $x is an integer. The PHP var_dump() function


returns the data type and value:

Example
<?php
$x = 5985;
var_dump($x);
?>

PHP Float
A float (floating point number) is a number with a decimal point or a number
in exponential form.

In the following example $x is a float. The PHP var_dump() function returns


the data type and value:

Example
<?php
$x = 10.365;
var_dump($x);
?>

PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.

$x = true;
$y = false;

Booleans are often used in conditional testing. You will learn more about
conditional testing in a later chapter of this tutorial.
PHP Array
An array stores multiple values in one single variable.

In the following example $cars is an array. The PHP var_dump() function


returns the data type and value:

Example
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>

You will learn a lot more about arrays in later chapters of this tutorial.

PHP Object
Classes and objects are the two main aspects of object-oriented
programming.

A class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the properties and
behaviors from the class, but each object will have different values for the
properties.

Let's assume we have a class named Car. A Car can have properties like
model, color, etc. We can define variables like $model, $color, and so on, to
hold the values of these properties.

When the individual objects (Volvo, BMW, Toyota, etc.) are created, they
inherit all the properties and behaviors from the class, but each object will
have different values for the properties.

If you create a __construct() function, PHP will automatically call this


function when you create an object from a class.
Example
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}

$myCar = new Car("black", "Volvo");


echo $myCar -> message();
echo "<br>";
$myCar = new Car("red", "Toyota");
echo $myCar -> message();
?>

PHP NULL Value


Null is a special data type which can have only one value: NULL.

A variable of data type NULL is a variable that has no value assigned to it.

Tip: If a variable is created without a value, it is automatically assigned a


value of NULL.

Variables can also be emptied by setting the value to NULL:

Example
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>

You might also like