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

PHP Regular Expressions

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
$pattern = "/^[a-z]+$/";
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
$email = "[email protected]";
if (preg_match("/^\S+@\S+\.\S+$/", $email)) {
    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
$text = "Contact #alice and #bob for details";
preg_match_all("/#(\w+)/", $text, $matches);
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
$name = "Doe, Jane";
$result = preg_replace("/(\w+), (\w+)/", "$2 $1", $name);
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
$text = "Hello World";
var_dump(preg_match("/hello/i", $text));
?>

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.