RegEx & RegEx Functions
RegEx finds patterns in strings — emails, phone numbers, passwords. PHP wraps patterns in delimiters like /pattern/.
Regular Expressions — pattern matching
RegEx finds patterns in strings — emails, phone numbers, passwords. PHP wraps patterns in delimiters like /pattern/.
Real-life example: RegEx is a bouncer with a dress code list — only strings matching the pattern get in.
<?php
$text = "Contact: asha@knowvora.com";
// preg_match — find first match
if (preg_match("/[a-z]+@[a-z]+\.[a-z]+/i", $text, $matches)) {
echo "Found email: " . $matches[0];
}
?>Common RegEx functions
preg_match() checks if pattern exists. preg_match_all() finds all matches. preg_replace() swaps matched text. preg_split() splits by pattern.
Real-life example: preg_replace is find-and-replace in Word. preg_split is cutting a rope wherever you see a knot.
<?php
$phone = "Call 98765-43210 today";
// Replace digits with X
$masked = preg_replace("/\d/", "X", $phone);
echo $masked;
// Split by comma or space
$tags = "php, mysql ajax";
$parts = preg_split("/[,\s]+/", $tags);
print_r($parts);
?>Validation with RegEx
Use RegEx for format checks but prefer filter_var() for emails and URLs when possible — it is simpler and well tested.
Real-life example: Checking password strength with RegEx is like a gym trainer — at least 8 chars, one number, one symbol.
<?php
$password = "Rishtaara1!";
$strong = preg_match(
"/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/",
$password
);
echo $strong ? "Strong password" : "Weak password";
?>