PHP Regular Expressions

By Vijay

By Vijay

Image
I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated July 4, 2025
Edited by Kamila

Edited by Kamila

Image
Kamila is an AI-based technical expert, author, and trainer with a Master’s degree in CRM. She has over 15 years of work experience in several top-notch IT companies. She has published more than 500 articles on various Software Testing Related Topics, Programming Languages, AI Concepts,…

Learn about our editorial policies.

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

Getting Started with PHP Regular Expressions

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:

  1. POSIX (Portable Operating System Interface) standard
  2. 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:

MetacharacterNameDescription
1\BackslashA general escape character.
2^CircumflexAn assert beginning of the subject.
3$DollarAn assert end of the subject or before a terminating newline.
4.DotAny character (including a non-printing character) except a newline.
5[]Square bracketsCharacter class definition.
6|Vertical barAny one of the patterns separated by |.
7()ParenthesisA subpattern.
8?Question markZero or more quantifiers.
9*AsteriskZero or more quantifiers.
10+Plus signOne or more quantifiers.
11{ }Curly bracketsMin/max quantifiers.
12HyphenA 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:

ChacharacterDescription
1\aAlarm
2\cxControl-x (x is any character)
3\eEscape
4\fFormfeed
5\nNewline
6\p{xx}A character with the xx property
7\P{xx}A character without the xx property
8\rCarriage return
9\RLine break
10\tTab
11\xhhA character with hex code hh
12\dddA character with octal code ddd, or a backreference
13\040A space
14\40A space
15\7A backreference
16\11A tab or a backreference
17\011A tab
18\0113A tab followed by the character 3
19\113The character with octal code 113
20\377A byte consisting entirely of 1 bit
21\81A 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:

ChacharacterDescription
1\dThe \d character matches a digit from 0 to 9.
2\DThe \D character matches a non-digit.
3\hThe \h character matches a horizontal whitespace character.
4\HThe \H character matches a character which is not a horizontal whitespace character.
5\sThe \s character matches a whitespace character like space, tab and newline.
6\SThe \S character matches a non-whitespace character.
7\vThe \v character matches a vertical whitespace character.
8\VThe \V character matches a character which is not a vertical whitespace character.
9\wThe \w character matches a word character like a-z, A-Z, 0-9 and _
10\WThe \W character matches a non-word character.

Usage 4: Simple assertions as shown below:

CharacterDescription
1\bWord boundary
2\BNot a word boundary
3\AStart of the subject
4\ZEnd of the subject or newline at end
5\zEnd of the subject
6\GFirst matching position in the subject

Modifiers

Modifiers specify how a search needs to be performed.

The following table shows Pattern Modifiers:

ModifierNameDescription
1iPCRE_CASELESSPerforms a case-insensitive search.
2mPCRE_MULTILINEPerforms a multiline search.
3sPCRE_DOTALLThe dot metacharacters within the pattern match all characters, as well as newlines.
4xPCRE_EXTENDEDThe whitespace characters within the pattern are ignored with a few exceptions.
5APCRE_ANCHOREDThe pattern is forced to be anchored.
6DPCRE_DOLLAR_ENDONLYThe $ metacharacters within the pattern match at the very end of the string.
7SThis is for extra analysis.
8UPCRE_UNGREEDYInverts the “greediness” of the quantifiers.
9XPCRE_EXTRAProvides more functionality of PCRE that is incompatible with Perl.
10JPCRE_INFO_JCHANGEDAllows duplicate names for subpatterns.
11uPCRE_UTF8Provides more functionality of PCRE that is incompatible with Perl.

Brackets

Brackets state a range of characters as shown below:

ExpressionDescription
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:

FunctionDescription
1preg_filter()The preg_filter() function conducts a regex search and replace.
2preg_grep()The preg_grep() function returns the array elements that match the pattern.
3preg_last_error()The preg_last_error() function returns the error code of the lastly execute PCRE regular expression.
4preg_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).
5preg_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.
6preg_quote()The preg_quote() function quotes the regular expression characters.
7preg_replace()The PHP preg_replace() function conducts a regular expression search and replace.
8preg_replace_callback()The PHP preg_replace_callback() function conducts a regex search and replaces using a callback.
9preg_replace_callback_array()The PHP preg_replace_callback_array() function conducts a regex search and replaces using callbacks.
10preg_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.

PREV Tutorial | NEXT Tutorial

Was this helpful?

Thanks for your feedback!

READ MORE FROM THIS SERIES:



Leave a Comment