PHP Regular Expressions
Regular expressions let you search, validate, and transform strings with powerful pattern matching. PHP uses PCRE (Perl Compatible Regular Expressions) via preg_* functions.
preg_match — Test If Pattern Matches
<?php
$email = 'rahul@ezycoders.in';
// Returns 1 if match, 0 if no match, false on error
if (preg_match('/^[\w.+-]+@[\w-]+\.[a-z]{2,}$/i', $email)) {
echo "Valid email!";
}
// Capture groups with third argument
$date = '2026-03-15';
if (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $date, $matches)) {
// $matches[0] = full match, [1] = year, [2] = month, [3] = day
echo "Year: {$matches[1]}, Month: {$matches[2]}, Day: {$matches[3]}";
}
// Named groups — much more readable
preg_match('/^(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})$/', $date, $m);
echo $m['year'] . '-' . $m['month'] . '-' . $m['day'];
preg_match_all — Find All Occurrences
<?php
$html = 'Visit <a href="https://php.net">PHP</a> and <a href="https://js.org">JS</a>';
$count = preg_match_all('/href="([^"]+)"/', $html, $matches);
echo "Found $count links:\n";
print_r($matches[1]); // ['https://php.net', 'https://js.org']
preg_replace — Find and Replace
<?php
// Replace all whitespace sequences with single space
$clean = preg_replace('/\s+/', ' ', ' Hello World ');
// 'Hello World'
// Remove HTML tags
$text = preg_replace('|<[^>]+>|', '', '<p>Hello <strong>World</strong></p>');
// 'Hello World'
// Back-references in replacement: $1 $2 or ${1}
$date = '15/03/2026';
$iso = preg_replace('/(\d{2})\/(\d{2})\/(\d{4})/', '$3-$2-$1', $date);
// '2026-03-15'
// preg_replace_callback — complex replacements with logic
$result = preg_replace_callback('/\d+/', function($m) {
return $m[0] * 2; // double every number found
}, 'I have 5 cats and 3 dogs');
// 'I have 10 cats and 6 dogs'
Common Patterns
<?php
$patterns = [
'email' => '/^[\w.+-]+@[\w-]+\.[a-z]{2,}$/i',
'phone_in' => '/^(\+91|0)?[6-9]\d{9}$/',
'url' => '/^https?:\/\/[\w.-]+\.[a-z]{2,}/i',
'slug' => '/^[a-z0-9]+(?:-[a-z0-9]+)*$/',
'ip' => '/^(\d{1,3}\.){3}\d{1,3}$/',
'date_iso' => '/^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$/',
];
function validate(string $type, string $value): bool {
global $patterns;
return isset($patterns[$type]) && preg_match($patterns[$type], $value) === 1;
}
validate('email', 'rahul@ezycoders.in'); // true
validate('phone_in', '9876543210'); // true
validate('slug', 'php-guide-2026'); // true
Q: What is the difference between preg_match and preg_match_all?
preg_match finds only the first match and stops. preg_match_all finds all matches in the string. Use preg_match for validation (does it match?), use preg_match_all for extraction (find all occurrences).
Q: What does the /i flag do?
It makes the pattern case-insensitive. /php/i matches PHP, php, Php, pHp etc. Other common flags: /m (multiline — ^ and $ match line boundaries), /s (dotall — . matches newline too), /x (extended — allows whitespace and comments in pattern).
Comments (0)
No comments yet. Be the first!
Leave a Comment