What Is A Regular Expression
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.
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 = "/school/";
In the example above, / is the delimiter, school is the pattern that is being searched for, and i is a modifier that
makes the search case-insensitive.
The delimiter can be any character that is not a letter, number, backslash or space. The most common delimiter
is the forward slash (/), but when your pattern contains forward slashes it is convenient to choose other
delimiters such as # or ~.
Regular Expression Functions
PHP provides a variety of functions that allow you to use regular expressions.
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,
preg_replace() Returns a new string where matched patterns have been replaced
Using preg_match()
The preg_match() function will tell you whether a string contains matches of a pattern.
Example
$pattern = "/school/";
The preg_match_all() function will tell you how many matches were found for a pattern in a string.
Example
Use a regular expression to do a case-insensitive count of the number of occurrences of "ain" in a string:
Using preg_replace()
The preg_replace() function will replace all of the matches of the pattern in a string with another string.
Example
$pattern = "/microsoft/i";
Expression Description i
[A-z] Find any character alphabetically between a specified upper-case letter and a specified Try it »
lower-case letter
[A-Z] Find any character alphabetically between two upper-case letters. Try it »
[123] Find one or many of the digits inside the brackets Try it »
Metacharacters
| Find a match for any one of the patterns separated by | as in: cat|dog|fish
Try it »
ML05 AA 1234
Quantifiers
Grouping
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.
Example
Use grouping to search for the word "banana" by looking for ba followed by two instances of na:
$pattern = "/ba(na){3}/i";
Example:
Remove special symbol from any given string
1. Empty String
2. Validate String
3. Validate Numbers
4. Validate Email
5. Validate URL
6. Input length
7.
Empty String
The code below checks that the field is not empty. If the user leaves the required field empty, it will show an
error message. Put these lines of code to validate the required field.
if (emptyempty ($_POST["name"])) {
echo $errMsg;
} else {
$name = $_POST["name"];
Validate String
The code below checks that the field will contain only alphabets and whitespace, for example - name. If the
name field does not receive valid input from the user, then it will show an error message:
echo $ErrMsg;
} else {
echo $name;
Validate Number
The below code validates that the field will only contain a numeric value. For example - Mobile no. If
the Mobile no field does not receive numeric data from the user, the code will display an error message:
echo $ErrMsg;
} else {
echo $mobileno;
Validate Email
A valid email must contain @ and . symbols. PHP provides various methods to validate the email address. Here,
we will use regular expressions to validate the email address.
The below code validates the email address provided by the user through HTML form. If the field does not
contain a valid email address, then the code will display an error message:
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^";
echo $ErrMsg;
} else {
The input length validation restricts the user to provide the value between the specified range, for Example -
Mobile Number. A valid mobile number must have 10 digits.
The given code will help you to apply the length validation on user input:
echo $ErrMsg;
} else {
Validate URL
The below code validates the URL of website provided by the user via HTML form. If the field does not contain
a valid URL, the code will display an error message, i.e., "URL is not valid".
$websiteURL = $_POST["website"];
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
echo $websiteErr;
} else {
echo "Website URL is: " .$websiteURL;
The below code validates that the user click on submit button and send the form data to the server one of the
following method - get or post.
if (isset ($_POST['submit']) {
if ($_SERVER["REQUEST_METHOD"] == "POST") {
} else {
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 = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
The preg_match() function searches a string for pattern, returning true if the pattern exists, and false
otherwise.
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";
}
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";
}
What Is the Use of Session in PHP?
A session in PHP allows the webserver to get the information about when you started a website, what you were
doing, when you closed the website and other related information. It is required because, unlike the PC or
mobile, the webserver does not have any information about you. That’s where sessions come into the picture.
These sessions have session variables that store all the necessary information into a temporary file. By default, it
will destroy this file when you close the website. Thus, to put it simply, a session in PHP helps in storing
information about users and makes the data available to all the pages of a website or application until you close
it.
• It creates a random 32 digit hexadecimal value as an identifier for that particular session. The identifier
value will look something like 4af5ac6val45rf2d5vre58sd648ce5f7.
• It sends a cookie named PHPSESSID to the user’s system. As the name gives out, the PHPSESSID
cookie will store the unique session id of the session.
• A temporary file gets created on the server and is stored in the specified directory. It names the file on
the hexadecimal id value prefixed with sess_. Thus, the above id example will be held in a file called
sess_4af5ac6val45rf2d5vre58sd648ce5f7.
PHP will access the PHPSESSID cookie and get the unique id string to get session variables’ values. It will then
look into its directory for the file named with that string.
When you close the browser or the website, it terminates the session after a certain period of a predetermined
time.
You can start a session in PHP by using the session_start() function. This function will, by default, first check
for an existing session. If a session already exists, it will do nothing, but it will create one if there’s no pre-
existing session available.
To set session variables, you can use the global array variable called $_SESSION[]. The server can then access
these global variables until it terminates the session. Now that you know what a session is in PHP and how to
start one, it’s time to look at an example and see how it works.
Note: It is always recommended to put the session_start() function as the first line in your code, even before any
HTML tags.
In the example below, you will start a session that will count how many times you have visited a website page.
For this, you will create a session variable named counter.
<?php
session_start();
$_SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
<html>
<head>
</head>
<body>
</body>
</html>
Output:
You can copy-paste this code in a .php file and load it several times to see the number in the counter variable see
it in action.
You can access a session variable’s value by using the global variable $_SESSION. In the example stated
below, you will create another session with a variable that stores your name.
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["name"] = "Simplilearn";
?>
</body>
</html>
Output:
Now that the variable is set, you will access it from another file. Create another file and write the following code
to access the name variable you have just set.
Note: Load both the pages without closing the browser, as it will end the session.
<?php
session_start();
?>
<html>
<body>
<?php
?>
</body>
</html>
Output:
Although the web server will terminate the session by default upon closing the browser, you can also destroy it
manually. Two functions can help you achieve this.
• session_destroy(): Calling this function will eliminate all the session variables
• unset(): Calling this function will kill only the specified session variable
You can also use the session_unset() function to remove all the variables of a session. Let’s look at how to
destroy the counter variable that you have created in one of the sessions above.
<?php
unset($_SESSION[‘counter’]);
?>
This will end only the counter variable, but not the others if there are any.
<?php
session_destroy();
?>
The PHP session_destroy() function does not accept any parameter. Simply calling this function will destroy the
entire session in PHP.