English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP Regular Expressions

In this tutorial, you will learn how regular expressions work and how to use them efficiently for pattern matching in PHP.

What is a regular expression

Regular expressions are commonly referred to as “ regex ”or “ RegExp Regular expressions, often abbreviated as 'regex', are a special format of text strings used to search for patterns within text. Regular expressions are one of the most powerful tools available today, capable of effectively processing and manipulating text. For example, they can be used to validate the format of user input data (such as names, email addresses, phone numbers, etc.) to ensure correctness, to find or replace matching strings within text content, and more.

PHP(版本5.3PHP (versionand higher versions) support Perl-style regular expressions through its preg_ function series. Why use Perl-style regular expressions? Because Perl (Practical Extraction and Reporting Language

)is the first mainstream programming language to provide integrated support for regular expressions and is known for its powerful support for regular expressions as well as exceptional text processing and manipulation capabilities.

Before delving into the world of regular expressions, let's first briefly introduce the commonly used PHP built-in pattern matching features.Function
Descriptionpreg_match()
Perform regular expression matching.preg_match_all()
Perform global regular expression matching.preg_replace()
Perform a regular expression search and replace.preg_grep()
Return the elements of the input array that match the pattern.preg_split()
Split a string into substrings using regular expressions.preg_quote()

Quote the regular expression characters found in the string. Note:

The PHP preg_match() function stops searching after finding the first match, while the preg_match_all() function continues searching to the end of the string and finds all possible matches, rather than stopping at the first match.

Regular expression syntaxRegular expression syntax includes the use of special characters (do not confuse withHTML special characters * Ambiguous). Characters with special meaning in regular expressions are: + ?

[ ] ( ) { } ^ $ | \ . Whenever you want to use them literally, you need to escape them with a backslash. For example, to match a period, you must write\. . All other characters are automatically taken in their literal sense.

The following sections describe various options that can be used to create patterns:

Character classes

A character class defined by square brackets surrounding a pattern, such as [ABC], always matches a single character from the specified list. This means that the expression [abc] only matches the characters a, b, or c.

You can also define a negative character class by enclosing the characters you want to exclude in parentheses (e.g.,-)with hyphen () to define a character range [0-9Let's look at some examples of character classes:

Regular expressionWhat can it do
[abc]Matches any one of the characters a, b, or c.
[^abc]Matches any character except a, b, or c.
[a-z]Matches any character from lowercase letter a to lowercase letter z.
[A-Z]Matches any character from uppercase letter A to uppercase letter Z.
[a-Z]Matches any character from lowercase letter a to uppercase letter Z.
[0-9]Matches any character from 0 to9a number between
[a-z0-9]Matches any character between a and z or 0 and9a single character between

The following example will show you how to use regular expressions and the PHP preg_match() function to find a pattern in a string:

<?php
$pattern = "/ca[kf]e/";
$text = "He was eating cake in the cafe.";
if(preg_match($pattern, $text)){
    echo "Match found!";
} else{
    echo "Match not found.";
}
?>
Test it out‹/›

Similarly, you can use the preg_match_all() function to find all matches in a string:

<?php
$pattern = "/ca[kf]e/";
$text = "He was eating cake in the cafe.";
$matches = preg_match_all($pattern, $text, $array);
echo $matches . " matches were found.";
?>
Test it out‹/›

Tip:Regular expressions are not exclusive to PHP. Languages like Java, Perl, Python, and others use the same symbols to find text patterns.

Predefined Character Classes

Some character classes (such as numbers, letters, and spaces) are used so frequently that they have shortcut names. The following table lists those predefined character classes:

ShortcutsWhat can it do
.Matches any single character except a newline character \n.
\dMatches any digit character. Identical to [0-9] identical.
\DMatches any non-digit character. Identical to [^0-9] identical
\sMatches any whitespace character (space, tab, newline, or carriage return). Identical to [\t\n\r]
\SMatches any non-whitespace character. Identical to [^\t\n\r]
\wMatches any word character (defined as a to z, A to Z, 0 to9and underscores). Identical to [a-zA-Z_0-9] identical
\WMatches any non-word character. Identical to [^a-Za-Z_0-9] identical

The following example will show you how to use regular expressions and the PHP preg_replace() function to find and replace spaces in a string:

<?php
$pattern = "/\s/";
$replacement = ""-";
$text = "Earth revolves around\nthe\tSun";
//Replace spaces, newlines, and tabs
echo preg_replace($pattern, $replacement, $text);
echo "<br>";
//Replace spaces only
echo str_replace(" ", "",-"$text");
?>
Test it out‹/›

Repeating Quantifiers

In the previous section, we learned how to match single characters in multiple ways. But what if you want to match multiple characters? For example, suppose you want to find a word containing one or more instances of the letter 'p', or a word with at least two 'p's, and so on. This is where quantifiers come into play. With quantifiers, you can specify the number of times a character should match in a regular expression.

The table below lists various methods for quantifying specific patterns:

Regular expressionWhat can it do
p+Match one or more letters 'p'.
p*Match zero or more occurrences of the letter 'p'.
p?Match zero or one occurrence of the letter 'p'.
p{2}Match exactly two letters 'p'.
p{2,3}Match at least two occurrences of the letter 'p', but no more than three.
p{2,}

Match twice or more2The letter 'p' appears twice.

p{3}Match up to three occurrences of the letter 'p'.

In the following example, the regular expression will use the PHP preg_split() function to split the string into commas, comma sequences, spaces, or their combinations:

<?php
$pattern = "/[\s,]+/";
$text = "My favourite colors are red, green and blue";
$parts = preg_split($pattern, $text);
 
//Loop through the $parts array and display the substrings
foreach($parts as $part){
    echo $part . "<br>";
}
?>
Test it out‹/›

Position anchors

In some cases, you may want to match at the beginning or end of a line, word, or string. To do this, you can use anchors. Two common anchors are the caret (^) representing the start of a string and the dollar sign ($) representing the end of a string.

Regular expressionWhat can it do
^pMatch with the letter 'p' at the beginning of the line.
p$Match with the letter 'p' at the end of the line.

In the following example, the regular expression will only display names that start with the letter 'J' in the name array using the PHP preg_grep() function:

<?php
$pattern = "/^J/";
$names = array("Jhon Carter", "Clark Kent", "John Rambo");
$matches = preg_grep($pattern, $names);
 
//Traverse the $matches array and display the matched names
foreach($matches as $match){
    echo $match . "<br>";
}
?>
Test it out‹/›

Pattern modifiers

Pattern modifiers allow you to specify how pattern matching is processed. Pattern modifiers are placed directly after the regular expression, for example, if you want to search for a pattern in a case-insensitive manner, you can use the i modifier as shown below:/pattern/i. The following table lists some of the most commonly used pattern modifiers.

ModifiersWhat can it do
iMake the match case-insensitive.
mModify the behavior of '^' and '$' to match newline character boundaries (i.e., the start or end of each line in a multiline string) rather than string boundaries.
gPerform a global match, that is, find all matches.
oEvaluate the expression only once.
sModify the behavior of '.' (dot) to match all characters, including newline characters.
xAllow you to use spaces and comments in regular expressions to maintain clarity.

The following example will show you how to use the i modifier and the PHP preg_match_all() function to perform a case-insensitive global search.

<?php
$pattern = "/color/i";
$text = "Color red is more visible than color blue in daylight.";
$matches = preg_match_all($pattern, $text, $array);
echo $matches . " matches were found.";
?>
Test it out‹/›

Similarly, the following example shows how to use the ^ anchor and m modifier with the PHP preg_match_all() function to match the start of each line in a multiline string.

<?php
$pattern = "/^color/im";
$text = "Color red is more visible than \ncolor blue in daylight.";
$matches = preg_match_all($pattern, $text, $array);
echo $matches . " matches were found.";
?>
Test it out‹/›

word boundary

Word boundary characters (\b) can help you search for patterns that start and/or end with the word. For example, the regular expression/\bcar/Match words that start with the pattern 'car' and match 'cart', 'carrot', or 'cartoon', but not 'oscar'.

Similarly, the regular expression/car\b/Match words ending with the pattern 'car' and match 'scar', 'oscar', or 'supercar', but not 'cart'. Similarly,/\bcar\b/Match words that start and end with 'car' and only match 'car'.

The following example will highlight words beginning with 'car' in bold:

<?php
$pattern = '/\bcar\w*/';
$replacement = '<b>$0</b>';
$text = 'Words beginning with car: cart, carrot, cartoon. Words ending with car: scar, oscar, supercar.';
echo preg_replace($pattern, $replacement, $text);
?>
Test it out‹/›

We hope you are already familiar with the basics of regular expressions. To learn how to use regular expressions to validate form data, please seePHP Form Validationtutorial.