PHP regular expressions (RegEx) let you search, validate, extract, and replace text using pattern strings powered by the PCRE engine. Every PHP regex pattern sits inside delimiter characters—most commonly forward slashes /pattern/ or #pattern#.
PHP provides three primary functions that cover almost every text-matching task.
preg_match($pattern, $subject, $matches): Checks if a pattern exists and captures the first match. Returns 1 on match, 0 on no match, or false on error.preg_match_all($pattern, $subject, $matches): Finds every occurrence in the string and stores all captured groups.preg_replace($pattern, $replacement, $subject): Replaces matched patterns with a new string.<?php
declare(strict_types=1);
$username = "dev_sadia99";
$isValidUsername = preg_match('/^[a-zA-Z][a-zA-Z0-9_]{3,19}$/', $username) === 1;
$logLine = "Orders: #1042, #1049, #1088";
preg_match_all('/#(\d+)/', $logLine, $orderMatches);
$rawPhone = "(555) 234-8910";
$digitsOnly = preg_replace('/\D+/', '', $rawPhone);
echo "Valid username: " . ($isValidUsername ? "Yes" : "No") . PHP_EOL;
print_r($orderMatches[1]);
echo "Digits only: {$digitsOnly}" . PHP_EOL;
Add the i modifier after the closing delimiter for case-insensitive matching, and u for UTF-8 Unicode support. For complex patterns with slashes (such as URLs), switch delimiters to ~ so you do not have to escape every /.
^ and $ anchors when validating: Without ^ and $, /[0-9]{4}/ matches "abc1234xyz" because the pattern exists inside the string.DOMDocument for HTML and filter_var($email, FILTER_VALIDATE_EMAIL) for emails instead of fragile regexes./(a+)+$/ can freeze your server on malformed input. Keep quantifiers specific.Characters like ., *, and / change the pattern meaning. Always escape dynamic strings with preg_quote($userString, '/') before interpolating them.
preg_split() do?preg_split('/[\s,]+/', $text) splits a string into an array using a regular expression delimiter—great for splitting by spaces, tabs, and commas together.
preg_match() return 1 instead of true?preg_match() returns an integer (1 for match, 0 for no match) or false if the pattern is invalid, so compare with === 1.
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.