Introduction
A sequence of characters that forms a search pattern is called regular expression. While searching or validating the format of any input field, for example, email, we use regular expressions. These can be complicated patterns or a single character.
Syntax:
We use delimiters, a pattern, and optional modifiers for making a regular expression string.
$exp = "/codingNinja/i";
Here,
Delimiters - '/'
Pattern - 'codingNinja' ( being serached for )
Modifier - 'i' ( make searchign case sensitive )
We can also have delimiters that are not letters, numbers, backslash, or spaces. Forward slash ('/') is the most common delimiter.
PHP regex functions
For using a regular expression, PHP provides us with various functions. the most used functions are
- preg_match()
This function returns one if we find the pattern in the string provided and 0 if not.
<?php
echo "<h2> Coding Ninja </h2></br>";
$str = "Visit CodingNinja";
$pattern = "/CodingNinja/i";
echo preg_match($pattern, $str); // Output 1
?>
Output-
- preg_match_all()
It finds the number of times the pattern occurs in the string ( can be 0 too ).
<?php
echo "<h2> Coding Ninja </h2></br>";
$str = "The rain in SPAIN falls.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str);
?>
Output-
- preg_replace()
This function returns a new string where the matched pattern is replaced with another string.
<?php
echo "<h2> Coding Ninja </h2></br>";
$str = "Visit google!";
$pattern = "/google/i";
echo preg_replace($pattern, "Coding Ninja", $str);
?>
Output-
Some more regex functions available in PHP are -
Functions | Descriptions |
preg_filter() | If matches are found, this function would return a string or array that replaces the matched pattern. |
preg_last_error() | When the most recent regular expression call fails it returns the error code. |
preg_replace_callback() | The substring returned by the callback replaces the matched pattern of the PHP regex expression; it returns a string. |
preg_split() | The use of matches of a regular expression as separators breaks the strings into an array. |