Summary - Regex
Build an email validation function with preg_match, preg_replace and character classes.
Summary - Regex
In this group you learned regular expressions. Three main functions: preg_match finds the first match, preg_match_all finds all, preg_replace replaces matches.
Patterns sit between delimiters: /.../. Character classes like [a-z] or \d; quantifiers *, +, ?, {n,m}. Parentheses form a capture group (...), referenced as $matches[1] or $1.
Two mini tasks now combine these: first clean an email, then validate it.
filter_var or preg_match?
PHP ships built-in filters for common patterns. For emails, filter_var($email, FILTER_VALIDATE_EMAIL) is used; if it returns false, the email is invalid.
This is shorter and faster for well-known formats like emails. But for your own rules (e.g. a phone number format), you write a custom pattern with preg_match.
Both are used in practice: first clean whitespace with preg_replace, then validate with filter_var.
Exercise Strip whitespace from an email
Write normalizeEmail(string $email): string. Use preg_replace with the pattern "/\s+/" and replacement "" to remove all whitespace, and return the result. The two echo calls below are already written.
Show example solution
string { return preg_replace("/\s+/", "", $email); }
Example solution:
<?php
// normalizeEmail: strip whitespace with preg_replace
// Define the normalizeEmail function
function normalizeEmail(string $email): string {
return preg_replace("/\s+/", "", $email);
}
echo normalizeEmail(" user @example.com ") . "\n";
echo normalizeEmail("user@exa mple.com") . "\n";
Exercise Validate an email format
Write isValidEmail(string $email): bool. Use preg_match with the pattern "/^[\w.]+@[\w]+\.[a-z]{2,}$/"; return true on match, false otherwise. Compare the result with === 1. The four echo calls below are already written.
Show example solution
bool { return preg_match("/^[\w.]+@[\w]+\.[a-z]{2,}$/", $email) === 1; }
Example solution:
<?php
// isValidEmail: validate email format with preg_match
// Define the isValidEmail function
function isValidEmail(string $email): bool {
return preg_match("/^[\w.]+@[\w]+\.[a-z]{2,}$/", $email) === 1;
}
echo isValidEmail("user@example.com") ? "valid\n" : "invalid\n";
echo isValidEmail("user@example") ? "valid\n" : "invalid\n";
echo isValidEmail("user@.com") ? "valid\n" : "invalid\n";
echo isValidEmail("@example.com") ? "valid\n" : "invalid\n";
Test yourself
-
Which function replaces all digits in a text with X?
- preg_match
- preg_replace
- preg_match_all
- filter_var
Show answer
preg_replace — Correct. preg_replace replaces matched pieces with new text.