A detailed explanation of PHP Regular Expressions with practical examples. Learn all about delimiters, metacharacters, modifiers & PHP Regex Functions to handle regular expressions:
In this tutorial, you will learn what a regular expression is, delimiters, metacharacters, uses of the backslash character, modifiers, character classes, PHP regex functions, and frequently asked questions (FAQs).
Please note that we have used PHP version 7 in all examples.
Let’s begin!
=> Check All PHP Tutorials Here
Table of Contents:
Getting Started with PHP Regular Expressions

What is a Regular Expression
A regular expression is a sequence of characters that helps to search text and carry out operations related to text replacement. It is commonly known as regex or RegExp. Regular expressions are case-sensitive by default. Furthermore, PHP provides built-in support for regular expressions.
Regular expressions are useful when validating user inputs like email, password, phone number, URL, IP address, etc. Further, they can use it for highlighting keywords in search results.
There are two types of syntax for writing regular expressions in PHP. They are:
- POSIX (Portable Operating System Interface) standard
- PCRE (Perl Compatible Regular Expressions) or Perl syntax
Out of the above two syntaxes, Perl syntax is the most widely used syntax.
You may use the PHP regex tester website (Click the URL) to test and debug your regex.
Delimiters
Delimiters are used to enclose the pattern in PCRE functions. The pattern is surrounded by two delimiters.
Non-alphanumeric, non-backslash, and non-whitespace characters are used as delimiters. The following list shows some of the characters that can be used as delimiters:
- / (forward slash)
- # (hash sign)
- ~ (tildes)
- + (plus sign)
- % (percentage sign)
Examples:
- /foo/
- /foo bar/
- #[a-z]#
- #http://#
- %[a-z]%
Metacharacters
In simple terms, a metacharacter is a character that has a special meaning. Metacharacters are commonly used in regular expressions.
The following table shows the standard regular expression metacharacters:
| Metacharacter | Name | Description | |
|---|---|---|---|
| 1 | \ | Backslash | A general escape character. |
| 2 | ^ | Circumflex | An assert beginning of the subject. |
| 3 | $ | Dollar | An assert end of the subject or before a terminating newline. |
| 4 | . | Dot | Any character (including a non-printing character) except a newline. |
| 5 | [] | Square brackets | Character class definition. |
| 6 | | | Vertical bar | Any one of the patterns separated by |. |
| 7 | () | Parenthesis | A subpattern. |
| 8 | ? | Question mark | Zero or more quantifiers. |
| 9 | * | Asterisk | Zero or more quantifiers. |
| 10 | + | Plus sign | One or more quantifiers. |
| 11 | { } | Curly brackets | Min/max quantifiers. |
| 12 | – | Hyphen | A range in the character class. |
Examples:
/[abc]/ matches abc
/1-3/ matches 1, 2, 3
/ex*/ matches expression, exercise, etc.
Uses of Backslash
The backslash (\) character has many uses. We have discussed four usages below:
Usage 1: As an escape character
If a backslash character is followed by a non-alphanumeric character, it removes any special meaning that it would have.
Example:
\* matches a * character in the pattern.
Usage 2: To encode non-printing characters in patterns in a visible way.
Another use of the backslash (\) is to encode non-printing characters in patterns in a visible way, as shown in the table below:
| Chacharacter | Description | |
|---|---|---|
| 1 | \a | Alarm |
| 2 | \cx | Control-x (x is any character) |
| 3 | \e | Escape |
| 4 | \f | Formfeed |
| 5 | \n | Newline |
| 6 | \p{xx} | A character with the xx property |
| 7 | \P{xx} | A character without the xx property |
| 8 | \r | Carriage return |
| 9 | \R | Line break |
| 10 | \t | Tab |
| 11 | \xhh | A character with hex code hh |
| 12 | \ddd | A character with octal code ddd, or a backreference |
| 13 | \040 | A space |
| 14 | \40 | A space |
| 15 | \7 | A backreference |
| 16 | \11 | A tab or a backreference |
| 17 | \011 | A tab |
| 18 | \0113 | A tab followed by the character 3 |
| 19 | \113 | The character with octal code 113 |
| 20 | \377 | A byte consisting entirely of 1 bit |
| 21 | \81 | A binary zero followed by the two characters 8 & 1, or a backreference |
Usage 3: To specify the generic character type, as shown in the table below:
| Chacharacter | Description | |
|---|---|---|
| 1 | \d | The \d character matches a digit from 0 to 9. |
| 2 | \D | The \D character matches a non-digit. |
| 3 | \h | The \h character matches a horizontal whitespace character. |
| 4 | \H | The \H character matches a character which is not a horizontal whitespace character. |
| 5 | \s | The \s character matches a whitespace character like space, tab and newline. |
| 6 | \S | The \S character matches a non-whitespace character. |
| 7 | \v | The \v character matches a vertical whitespace character. |
| 8 | \V | The \V character matches a character which is not a vertical whitespace character. |
| 9 | \w | The \w character matches a word character like a-z, A-Z, 0-9 and _ |
| 10 | \W | The \W character matches a non-word character. |
Usage 4: Simple assertions as shown below:
| Character | Description | |
|---|---|---|
| 1 | \b | Word boundary |
| 2 | \B | Not a word boundary |
| 3 | \A | Start of the subject |
| 4 | \Z | End of the subject or newline at end |
| 5 | \z | End of the subject |
| 6 | \G | First matching position in the subject |
Modifiers
Modifiers specify how a search needs to be performed.
The following table shows Pattern Modifiers:
| Modifier | Name | Description | |
|---|---|---|---|
| 1 | i | PCRE_CASELESS | Performs a case-insensitive search. |
| 2 | m | PCRE_MULTILINE | Performs a multiline search. |
| 3 | s | PCRE_DOTALL | The dot metacharacters within the pattern match all characters, as well as newlines. |
| 4 | x | PCRE_EXTENDED | The whitespace characters within the pattern are ignored with a few exceptions. |
| 5 | A | PCRE_ANCHORED | The pattern is forced to be anchored. |
| 6 | D | PCRE_DOLLAR_ENDONLY | The $ metacharacters within the pattern match at the very end of the string. |
| 7 | S | – | This is for extra analysis. |
| 8 | U | PCRE_UNGREEDY | Inverts the “greediness” of the quantifiers. |
| 9 | X | PCRE_EXTRA | Provides more functionality of PCRE that is incompatible with Perl. |
| 10 | J | PCRE_INFO_JCHANGED | Allows duplicate names for subpatterns. |
| 11 | u | PCRE_UTF8 | Provides more functionality of PCRE that is incompatible with Perl. |
Brackets
Brackets state a range of characters as shown below:
| Expression | Description | |
|---|---|---|
| 1 | [0-9] | Matches any decimal digit between zero and nine. |
| 2 | [a-z] | Matches any character from a (lowercase) to z (lowercase). |
| 3 | [A-Z] | Matches any character from A (uppercase) to Z (uppercase). |
| 4 | [a-Z] | Matches any character from a (lowercase) to Z (uppercase). |
| 5 | [a-z0-9] | Matches any character from a (lowercase) to z (lowercase), and from zero to nine. |
| 6 | [abc] | Matches any character from the given options; a, b, or c. |
| 7 | [^abc] | Matches any character apart from a, b, or c. |
Apart from the above ranges, you may use some other ranges as well.
Examples:
[1-4] – Matches any decimal digit between one and four.
[b-m] – Matches any character from b (lowercase) to m (lowercase).
PHP Regex Functions
PHP has several built-in functions to handle regular expressions, as shown in the table below:
| Function | Description | |
|---|---|---|
| 1 | preg_filter() | The preg_filter() function conducts a regex search and replace. |
| 2 | preg_grep() | The preg_grep() function returns the array elements that match the pattern. |
| 3 | preg_last_error() | The preg_last_error() function returns the error code of the lastly execute PCRE regular expression. |
| 4 | preg_match() | The PHP preg_match() function conducts a regular expression match. It returns 1 if the pattern was found, otherwise 0 (or false on failure). |
| 5 | preg_match_all() | The PHP preg_match_all() function conducts a global regular expression match. It returns the number of full pattern matches (maybe zero) or false on failure. |
| 6 | preg_quote() | The preg_quote() function quotes the regular expression characters. |
| 7 | preg_replace() | The PHP preg_replace() function conducts a regular expression search and replace. |
| 8 | preg_replace_callback() | The PHP preg_replace_callback() function conducts a regex search and replaces using a callback. |
| 9 | preg_replace_callback_array() | The PHP preg_replace_callback_array() function conducts a regex search and replaces using callbacks. |
| 10 | preg_split() | The preg_split() function splits a string by a regular expression. |
Given below are some examples of regular expression functions.
Example 1: preg_filter() function
<?php
$txt = 'John Doe';
$pattern = '/john/i';
echo preg_filter($pattern, 'Jane', $txt);
?>
Output:
Jane Doe
Example 2: preg_filter() function
<?php
$txt = 'John Doe';
$pattern = '/jack/i';
echo preg_filter($pattern, 'Jane', $txt);
?>
Output:
(no output)
Note: The PHP preg_filter() function and the PHP preg_replace() function work similarly, but the preg_filter() function only returns an output if only finds a match.
Example 3: preg_replace() function
<?php
$txt = 'John Doe';
$pattern = '/john/i';
echo preg_replace($pattern, 'Jane', $txt);
?>
Output:
Jane Doe
Example 4: preg_replace() function
<?php
$txt = 'John Doe';
$pattern = '/jack/i';
echo preg_replace($pattern, 'Jane', $txt);
?>
Output:
John Doe
Example 5: preg_grep() function
<?php
$animals = array("Lion","tiger","leopard","wolf","cheetah");
$result = preg_grep("/^l/i", $animals);
print_r($result);
?>
Output:
Array ( [0] => Lion [2] => leopard )
Example 6: preg_split() function
<?php
$txt = 'Software';
$chars = preg_split('//', $txt, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
?>
Output:
Array ( [0] => S [1] => o [2] => f [3] => t [4] => w [5] => a [6] => r [7] => e )
Example 7: preg_match() function
<?php
$user_email = "name@user.com";
if (preg_match("/^[0-9a-zA-Z.-_]+@[0-9a-zA-Z-]+\.[a-zA-Z.]{2,9}$/", $user_email)) {
echo "$user_email is valid.";
}else{
echo "$user_email is invalid.";
}
?>
Output:
name@user.com is valid.
Frequently Asked Questions
1. Can you use regex in PHP?
Yes, you can use regex in PHP. They are useful for searching text and carrying out text replacement operations.
2. What is a PHP regex?
A PHP regex (regular expression) is a sequence of characters that can be used for matching patterns.
3. What does [A-Z0-9] mean?
A PHP regex (regular expression) is a sequence of characters that can be used for matching patterns.
4. What does preg_match mean in PHP?
It is a function used to perform a regular expression match. It returns 1 if the pattern was found, otherwise 0 (or false on failure).
5. Which function is used to match all occurrences of patterns in a string?
The preg_match_all() function is used to match all occurrences of patterns in a string. It returns the number of full pattern matches (maybe zero) or false on failure.
6. What is the PHP preg_replace function do?
The PHP preg_replace() function conducts a regular expression search and replace.
Conclusion
A regular expression is a sequence of characters that helps to match patterns. They can be used for searching text and carrying out operations related to text replacement.
Some characters in regex have special meanings. Furthermore, PHP provides built-in support for regular expressions.






