PHP Regular Expressions
In this page:
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
$pattern = "/^[a-z]+$/";
var_dump(preg_match($pattern, "hello"));
?>
Login to try C/C++/Java/PHP code in the editor
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
$email = "[email protected]";
if (preg_match("/^\S+@\S+\.\S+$/", $email)) {
echo "Valid email format";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
$text = "Contact #alice and #bob for details";
preg_match_all("/#(\w+)/", $text, $matches);
print_r($matches[1]);
?>
Login to try C/C++/Java/PHP code in the editor
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
$name = "Doe, Jane";
$result = preg_replace("/(\w+), (\w+)/", "$2 $1", $name);
echo $result;
?>
Login to try C/C++/Java/PHP code in the editor
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
$text = "Hello World";
var_dump(preg_match("/hello/i", $text));
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: