0% found this document useful (0 votes)
4 views9 pages

What Is A Regular Expression

A regular expression is a sequence of characters that defines a search pattern used for text search and replace operations. In PHP, regular expressions are utilized through functions like preg_match(), preg_match_all(), and preg_replace() to validate input and manipulate strings. Sessions in PHP allow for the storage of user information across multiple pages, with session variables created and accessed through the $_SESSION global array.
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)
4 views9 pages

What Is A Regular Expression

A regular expression is a sequence of characters that defines a search pattern used for text search and replace operations. In PHP, regular expressions are utilized through functions like preg_match(), preg_match_all(), and preg_replace() to validate input and manipulate strings. Sessions in PHP allow for the storage of user information across multiple pages, with session variables created and accessed through the $_SESSION global array.
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/ 9

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 = "/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.

The most common functions are:

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

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 "school" in a string:

$str = "Visit chool";

$pattern = "/school/";

echo preg_match($pattern, $str);


Using preg_match_all()

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:

$str = "The rain in SPAIN falls mainly on the plains.";


$pattern = "/AIN/i";

echo preg_match_all($pattern, $str);

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 School in a string:

$str = "Visit Microsoft!";

$pattern = "/microsoft/i";

echo preg_replace($pattern, "School", $str);

Regular Expression Patterns

Brackets are used to find a range of characters:

Expression Description i

[abc] Find one or many of the characters inside the brackets

[^abc] Find any character NOT between the brackets Try it »

[a-z] Find any character alphabetically between two letters Try it »

[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 »

[0-5] Find any digits between the two numbers Try it »

[0-9] Find any digits

Metacharacters

Metacharacters are characters with a special meaning:

| Find a match for any one of the patterns separated by | as in: cat|dog|fish

Try it »

. Find any character Try it »


^ Finds a match as the beginning of a string as in: ^Hello Try it »

$ Finds a match at the end of the string as in: World$

ML05 AA 1234

Quantifiers

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

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:

$str = "Apples and bananas.";

$pattern = "/ba(na){3}/i";

echo preg_match($pattern, $str);

PHP String Exercises: Remove part of a string


Example:
<?php
$my_str = 'The quick brown fox jumps over the lazy dog';
// Define the original string.

echo str_replace("fox", " ", $my_str)."\n";


// Replace all occurrences of "fox" with a space in the original string and output the result.
?>

Example:
Remove special symbol from any given string

preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $String);

PHP Form Validation


An HTML form contains various input fields such as text box, checkbox, radio buttons, submit button, and
checklist, etc. These input fields need to be validated, which ensures that the user has entered information in all
the required fields and also validates that the information provided by the user is valid and correct.
There is no guarantee that the information provided by the user is always correct. PHP validates the data at the
server-side, which is submitted by HTML form. You need to validate a few things:

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"])) {

$errMsg = "Error! You didn't enter the 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:

$name = $_POST ["Name"];

if (!preg_match ("/^[a-zA-z]*$/", $name) ) {

$ErrMsg = "Only alphabets and whitespace are allowed.";

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:

$mobileno = $_POST ["Mobile_no"];

if (!preg_match ("/^[0-9]*$/", $mobileno) ){

$ErrMsg = "Only numeric value is allowed.";

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:

$email = $_POST ["Email"];

$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^";

if (!preg_match ($pattern, $email) ){

$ErrMsg = "Email is not valid.";

echo $ErrMsg;

} else {

echo "Your valid email address is: " .$email;

Input Length Validation

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:

$mobileno = strlen ($_POST ["Mobile"]);

$length = strlen ($mobileno);

if ( $length < 10 && $length > 10) {

$ErrMsg = "Mobile must have 10 digits.";

echo $ErrMsg;

} else {

echo "Your Mobile number is: " .$mobileno;

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)) {

$websiteErr = "URL is not valid";

echo $websiteErr;

} else {
echo "Website URL is: " .$websiteURL;

Button Click Validate

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']) {

echo "Submit button is clicked.";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

echo "Data is sent using POST method ";

} else {

echo "Data is not submitted";

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 = 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.

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";
}

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";
}
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.

What Happens When You Start a Session in PHP?

The following things occur when a session is started:

• 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.

How to Start a PHP Session?

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.

Example: How to Start a Session in PHP?

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();

if( isset( $_SESSION['counter'] ) ) {

$_SESSION['counter'] += 1;

}else {

$_SESSION['counter'] = 1;

$my_Msg = "This page is visited ". $_SESSION['counter'];

$my_Msg .= " time during this session.";


?>

<html>

<head>

<title>Starting a PHP session</title>

</head>

<body>

<?php echo ( $my_Msg ); ?>

</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.

How to Access Values From a Session in PHP?

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";

echo "Information set in a variable.<br/>";

?>

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

echo "User is: ".$_SESSION["name"];

?>

</body>

</html>

Output:

How to Destroy a Session in PHP?

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.

Example: Using unset() to Destroy a Session Variable

<?php

unset($_SESSION[‘counter’]);

?>

This will end only the counter variable, but not the others if there are any.

Example: Using session_destroy() to Destroy a Complete Session in PHP

<?php

session_destroy();

?>

The PHP session_destroy() function does not accept any parameter. Simply calling this function will destroy the
entire session in PHP.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy