← Back to PHP Course | Chapter 6: Strings | Lesson 5 of 8

PHP Regular Expressions

A regular expression is a secret code for describing a pattern in text, like 'three digits then a dash'. It lets PHP find or check words that fit the pattern, the way a metal detector finds only metal.
Syntax
php
preg_match("/pattern/", $subject, $matches);       // first match
preg_match_all("/pattern/", $subject, $matches);   // every match
$result = preg_replace("/pattern/", "replacement", $subject);

Basic Match Checking

Regular expressions describe a text pattern using special metacharacters, letting you match, extract, or validate strings that follow a shape rather than an exact literal value.

PHP's preg_* functions wrap the PCRE (Perl-Compatible Regular Expressions) engine, so the same pattern syntax you'd use in Perl or many other languages works here too.

Example: Basic Match Checking

php
<?php
// Declare `$pattern`, set to "/^[a-z]+$/"
$pattern = "/^[a-z]+$/";
// Print a detailed dump (with types) of `preg_match($pattern, "hello")`
var_dump(preg_match($pattern, "hello"));
?>

Finding All Matches

preg_match() searches a string for the first occurrence of a pattern and reports whether it was found, optionally filling an output array with the matched text and any captured groups.

It's the workhorse for validation checks like confirming an email address or phone number roughly matches an expected shape.

Example: Finding All Matches

php
<?php
// Declare `$email`, set to "[email protected]"
$email = "[email protected]";
// Check whether `preg_match("/^\S+@\S+\.\S+$/", $email)`
if (preg_match("/^\S+@\S+\.\S+$/", $email)) {
    // Print "Valid email format" to the output
    echo "Valid email format";
}
?>

Replacing Text with Patterns

preg_match_all() behaves like preg_match() but keeps scanning after the first hit, returning every match in the string instead of stopping at the first one.

Use it when you need to pull out all occurrences of a pattern, such as every hashtag or URL in a block of text.

Example: Replacing Text with Patterns

php
<?php
// Declare `$text`, set to "Contact #alice and #bob for details"
$text = "Contact #alice and #bob for details";
// Call `preg_match_all("/#(\w+)/", $text, $matches)`
preg_match_all("/#(\w+)/", $text, $matches);
// Print a human-readable dump of `$matches[1]`
print_r($matches[1]);
?>

Splitting String by Pattern

preg_replace() finds every match of a pattern and swaps it for replacement text, supporting backreferences so you can reuse captured groups inside the replacement.

This makes it useful for reformatting data, like turning 'lastname, firstname' into 'firstname lastname' in one call.

Example: Splitting String by Pattern

php
<?php
// Declare `$name`, set to "Doe, Jane"
$name = "Doe, Jane";
// Declare `$result`, set to `preg_replace("/(\w+), (\w+)/", "$2 $1", $name)`
$result = preg_replace("/(\w+), (\w+)/", "$2 $1", $name);
// Print `$result` to the output
echo $result;
?>

Pattern Validation

Delimiters (commonly forward slashes) wrap a pattern so PHP knows where it starts and ends, and modifier flags placed after the closing delimiter change matching behavior, like i for case-insensitive matching or m for treating each line separately with ^ and $.

Example: Pattern Validation

php
<?php
// Declare `$text`, set to "Hello World"
$text = "Hello World";
// Print a detailed dump (with types) of `preg_match("/hello/i", $text)`
var_dump(preg_match("/hello/i", $text));
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting the delimiters, like preg_match(abc, $s), which produces a warning because a pattern needs /.../.
  2. Forgetting that preg_match() returns 1, 0 or false, not an array of matches, so use the third argument to get them.
  3. Not escaping special characters such as . in the pattern, so /a.b/ also matches axb.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.