PHP Regular Expressions
In this page:
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
// 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"));
?>
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
// 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";
}
?>
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
// 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]);
?>
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
// 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;
?>
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
// 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));
?>
Login to try C/C++/Java/PHP code in the editor
- Forgetting the delimiters, like
preg_match(abc, $s), which produces a warning because a pattern needs/.../. - Forgetting that
preg_match()returns1,0orfalse, not an array of matches, so use the third argument to get them. - Not escaping special characters such as
.in the pattern, so/a.b/also matchesaxb.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: