In this article we are going to cover Regular Expression in PHP with Examples, Advantages and uses of Regular expressions,Operations in Regular Expression, Special Character Classes in Regular Expressions.
Table of Contents
What is Regular expression in PHP ?
Regular expression are commonly known as regex. These are nothing more than a pattern or a sequence of characters, which describe a special search pattern as text string. They are basically used in programming world algorithms for matching some loosely defined patterns to achieve some relevant tasks. Sometimes regexes are understood as a mini programming language with a pattern notation which allows the users to parse text strings.
A regular expression can be a single character, or more complicated pattern.
Regular expression can be used to perform all types of text search and text replace operations.
Advantages and uses of Regular expressions in PHP:
Regular expressions are used almost everywhere in today’s application programming.
- Regular expression helps the programmers to validate text string.
- It helps in searching specific string pattern and extracting matching results in a flexible manner.
- It effectively saves a lot of development time, which are in search of specific string pattern.
- With the help of in-built regexes functions, easy and simple solution are provided for identifying patterns.
- It helps in important user information validations like email address, phone numbers and IP address.
- Regexes are mostly used for browser detection, spam filteration , checking password strength and form validations.
Operations in Regular Expression in PHP:
Operator | Description |
^ | It denotes the start of string. |
$ | It denote the end of string. |
. | It denotes almost any single character. |
() | It denotes a group of expressions. |
[] | It finds a range of characters e.g, [abc] means x, y or z. |
[^] | It finds the items which are not in range e.g, [^abc] means NOT a, b or c. |
(dash) | It finds for character range within the given item range e.g, [a-z] means a through z. |
| (pipe) | It is the logical OR e.g, x | y means x OR y. |
? | It denotes zero or more of preceding character or item range. |
* | It denotes zero or more of preceding character or item range. |
+ | It denotes zero or more of preceding character or item range. |
{n} | It denotes exactly n times of preceding character or item range e.g, n{2}. |
{n, } | It denotes atleast n times of preceding character or item range e.g, n{2, }. |
{n, m} | It denotes atleast n but not more than m times e.g, n{2, 4} means 2 to 4 of n. |
\ | It denotes the escape character. |
Special Character Classes in Regular Expressions in PHP:
Special Character | Description |
\n | It denotes a new line. |
\r | It denotes a carriage return. |
\t | It denote a tab. |
\v | It denote a vertical tab. |
\f | It denote a form feed. |
\xxx | It denotes octal character xxx. |
\xhh | It denote hex character hh/ |
Predefined functions or Regex library in PHP:
Let us look into the quick cheat sheet of predefined functions for regular expressions in PHP.
Function | Defination |
Preg_match() | This function searches for a specific pattern against some string. It return true if pattern exists and false otherwise. |
Preg_match_all() | This function searches for all the occurrences of string pattern against the string. This function is very useful for search and replace. |
preg_replace() | The preg_replace() function is similar to the preg_replace() function, except that the regular expressions can be used in search and replace. |
preg_split() | This function exactly works like split() function except the condition is that it accepts regular expression as an input parameter for pattern. Mainly it divides the string by a regular expression. |
preg_grep() | The preg_grep() function finds all the elements of input array and returns the array elements matched with regexp (relational expression) pattern. |
preg_quote() | Quote the regular expression characters. |
Regular Expression Modifiers in PHP:
Modifiers can change how a search is performed.
Modifier | Description |
i | Performs a case-insensitive search |
m | Performs a multiple search |
u | Enables correct matching of UTF-8 encoded patterns |
Regular Expression Patterns in PHP:
Bracket are used to find a range of characters:
Expression | Description |
[abc] | Find one character from the options between the brackets |
[^abc] | Find any character NOT between the brackets |
[0-9] | Find one character from the range 0 to 9 |
Using preg_match() function in PHP:
This function will tell you whether a string contains matches of a pattern.
Example of preg_match() function:
<!DOCTYPE html>
<html>
<body>
<?php
$pattern = '/^[a-zA-Z ]*$/';
$str = 'Welcome to FOSSTechNix';
if(preg_match($pattern, $str)) {
echo("Name string matching with"
. " regular expression");
}
else {
echo("Only letters and white space"
. " allowed in name string");
}
?>
</body>
</html>
Output:
Name string matching with regular expression
Using preg_match_all()function in PHP:
This function will tell you how many matches were found for a pattern in a string.
Example of using preg_match_all() function:
<!DOCTYPE html>
<html>
<body>
<?php
$pattern = "/<b>(.*)<\/b>/U";
$str = "Name: <b>Shweta</b> Position: <b>Developer</b>";
preg_match_all($pattern, $str, $output);
echo $output[0][0]." <br> ".$output[0][1]."\n";
?>
</body>
</html>
Output:
Shweta
Developer
Using preg_replace() function in PHP:
This function will replace all of the matches of the pattern in a string with another string.
Example of preg_replace() function:
<?php
$pattern = "([0-9]+)";
$str = "Completed diploma in 2016";
$replacestr = "2019";
$original = preg_replace($pattern, $replacestr, $str);
echo $original;
?>
Output:
Completed diploma in 2019
Grouping in PHP :
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 of grouping in PHP:
<?php
$str = "Apples and bananas.";
$pattern = "/ba(na){2}/i";
$original = preg_match($pattern, $str);
echo $original;
?>
Output:
1
Conclusion:
In this article we have covered Regular Expression in PHP with Examples, Advantages and uses of Regular expressions,Operations in Regular Expression, Special Character Classes in Regular Expressions.
Related Articles:
- Introduction about PHP [PHP 7]
- Date and Time in PHP with Examples [2 Steps]
- 3 Data Types in PHP with Examples
- Form Validation in PHP with Examples
- 3 Types of Arrays in PHP with Examples
- 4 Types of Loop in PHP with Examples
- 4 Types of String in PHP with Examples
- Cookies in PHP with Examples [2 Steps]
- File Upload in PHP with Examples
- File Handling in PHP with Examples
Reference:
Regular Expression in PHP official page