PHP Tutorial
PHP Flow Control
PHP Functions
PHP String
PHP Array
PHP Date Time
PHP Object Oriented
Regular Expression
PHP Cookie & Session
PHP Error & Exception handling
MySQL in PHP
PHP File Directory
PHP Image Processing
Regular expressions (regex) are a powerful tool that allow for pattern matching and manipulation of text. In PHP, regular expressions are mainly handled with the preg_*
family of functions.
Syntax:
In PHP, regular expressions are represented as strings. The pattern itself is wrapped between delimiters, which can be any non-alphanumeric, non-backslash, non-whitespace character. After the closing delimiter, you can specify various options:
i
: Makes the match case insensitive.m
: Changes ^
and $
to match the start and end of a line, not just the string.s
: Changes .
to match all characters, including newlines.x
: Allows for comments and whitespace in the pattern for clarity.u
: Treats the pattern and subject strings as UTF-8.Example:
Here's an example of a regular expression that matches a simple email address:
$email = 'test@example.com'; $pattern = '/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i'; if (preg_match($pattern, $email)) { echo 'Valid email address.'; } else { echo 'Invalid email address.'; }
In this example, preg_match()
is used to test whether the $email
string matches the pattern. If it does, the function returns 1
, otherwise it returns 0
.
Common preg_*
functions:
preg_match(pattern, subject)
: Returns 1
if pattern
matches subject
, 0
if it doesn't, or false
if an error occurred.preg_match_all(pattern, subject)
: Similar to preg_match()
, but finds all matches and returns them in an array.preg_replace(pattern, replacement, subject)
: Searches subject
for pattern
and replaces it with replacement
.preg_split(pattern, subject)
: Splits subject
by pattern
and returns an array of the parts.Learn More:
To learn more about regular expressions, I highly recommend checking out resources like https://regex101.com/, which allows you to test your regular expressions in real-time, and provides explanations for your patterns. Regular expressions can get very complex and are a powerful tool in any developer's toolbox, so they're definitely worth learning.
How to use preg_match
in PHP:
preg_match
to perform a regular expression match.$pattern = '/\d{2}/'; $subject = 'A23B'; if (preg_match($pattern, $subject, $matches)) { echo 'Match found: ' . $matches[0]; } else { echo 'No match found.'; }
PHP regex cheat sheet:
// Example regex cheat sheet $pattern = '/[a-z]+\d{2,4}/i';
Validate email with regular expression in PHP:
$email = 'user@example.com'; if (preg_match('/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/', $email)) { echo 'Valid email address.'; } else { echo 'Invalid email address.'; }
PHP preg_replace
example:
preg_replace
to perform regular expression-based replacements.$text = 'Hello World'; $newText = preg_replace('/\bWorld\b/', 'Universe', $text); echo $newText; // Outputs: Hello Universe
Regular expression modifiers in PHP:
i
for case-insensitivity or m
for multiline matching.$pattern = '/pattern/i';
PHP regex character classes:
\d
for digits or \w
for word characters.$pattern = '/[0-9a-fA-F]/';
Capture groups in PHP regex:
$text = 'Date: 2022-01-01'; if (preg_match('/Date: (\d{4}-\d{2}-\d{2})/', $text, $matches)) { echo 'Matched date: ' . $matches[1]; }
PHP regex lookahead and lookbehind:
(?=...)
and lookbehind (?<=...)
assertions for more complex matching.$text = 'PHP is powerful'; $pattern = '/\bPHP\b(?=\s+is)/'; if (preg_match($pattern, $text)) { echo 'Match found.'; }
Common regex patterns in PHP:
// Example for matching URLs $urlPattern = '/^https?:\/\/[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/'; // Example for extracting phone numbers $text = 'Contact us at (555) 123-4567'; $phonePattern = '/\(\d{3}\) \d{3}-\d{4}/'; preg_match($phonePattern, $text, $matches); echo 'Phone number: ' . $matches[0];