preg_* Functions)Regular expressions (RegEx) are pattern strings used to search, validate, match, and replace complex text formatting in PHP using PCRE (Perl Compatible Regular Expressions).
preg_match($pattern, $subject, $matches): Checks if pattern matches text (returns 1 or 0).preg_match_all($pattern, $subject, $matches): Finds all pattern occurrences in string.preg_replace($pattern, $replacement, $subject): Replaces matching text pattern.preg_split($pattern, $subject): Splits string into array by regex delimiter.flowchart LR
A["Pattern Delimiter '/'"] --> B["Regex Expression '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}'"]
B --> C["Pattern Delimiter '/'"]
C --> D["Modifiers 'i' (Case-Insensitive)"]
<?php
declare(strict_types=1);
// 1. Validating Username Format (Alphanumeric & Underscores, 3-16 chars)
$username = "maksudur_dev";
$usernamePattern = '/^[a-zA-Z0-9_]{3,16}$/';
if (preg_match($usernamePattern, $username)) {
echo "Username '$username' is VALID.
";
} else {
echo "Username '$username' is INVALID.
";
}
// 2. Extracting Phone Numbers using preg_match_all
$text = "Contact support at 555-0199 or emergency desk at 555-0822.";
$phonePattern = '/\d{3}-\d{4}/';
preg_match_all($phonePattern, $text, $matches);
echo "Extracted Phone Numbers: " . implode(", ", $matches[0]) . "
";
// 3. Sanitizing Multiple Spaces with preg_replace
$messyString = "PHP is a great language.";
$cleanString = preg_replace('/\s+/', ' ', $messyString);
echo "Cleaned String: '$cleanString'
";
/pattern/ or #pattern# consistently.^ for string start, $ for string end, and + for 1 or more occurrences.filter_var($email, FILTER_VALIDATE_EMAIL) for email validation instead of writing long fragile custom regexes.Write a preg_match() call that validates whether a string $postalCode matches a 5-digit ZIP code pattern (/^\d{5}$/)!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.