Common Regex Patterns
debt(d7/e1/b3/t7)
Closest to 'only careful code review or runtime testing' (d7) — regex101 helps test patterns manually and phpstan won't flag a buggy email regex; broken validation typically surfaces when real users with unusual addresses are rejected.
Closest to 'one-line patch or single-call swap' (e1) — quick_fix says replace custom regex with filter_var(FILTER_VALIDATE_EMAIL), a single-call swap.
Closest to 'localised tax' (b3) — validation patterns tend to be sprinkled in form handlers and input layers; not architectural but more than a single utility, and copy-pasted regex tends to proliferate.
Closest to 'serious trap' (t7) — the misconception (a regex matching most emails is 'good enough') contradicts reality: RFC 5321 email format is hundreds of lines and format validity says nothing about deliverability; the obvious DIY approach is reliably wrong.
Also Known As
TL;DR
Explanation
Tempting but often wrong: email regex. RFC 5321 email addresses are almost impossible to fully validate with regex — use filter_var($email, FILTER_VALIDATE_EMAIL) in PHP. URL validation: parse_url() is more reliable than regex. Useful regex patterns: UUID validation, slug validation, credit card format (not validation), postal codes for specific countries. The key insight: regex validates format, not semantics — a regex-valid email may not exist.
Common Misconception
Why It Matters
Common Mistakes
- Custom email regex that rejects valid addresses — addresses with +, quoted strings, or long TLDs.
- Using regex for format validation where PHP built-ins exist — filter_var(), parse_url(), ctype_* are tested and correct.
- Copy-pasting regex without understanding — a pattern that works for one locale breaks for another.
- URL regex that misses edge cases — IPv6 addresses, unicode domains, non-standard ports.
Code Examples
// Custom email regex — rejects valid addresses:
if (!preg_match('/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/', $email)) {
die('Invalid email');
}
// Rejects: user+tag@example.com ✗ (valid)
// Rejects: user@subdomain.co.uk ✓ (matches, OK)
// Rejects: user@xn--nxasmq6b.com ✗ (valid IDN)
// Use PHP built-ins:
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) die('Invalid email');
if (!filter_var($url, FILTER_VALIDATE_URL)) die('Invalid URL');
// Regex for things built-ins don't cover:
$uuidPattern = '/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i';
$slugPattern = '/^[a-z0-9]+(?:-[a-z0-9]+)*$/';
$hexColour = '/^#([0-9a-f]{3}|[0-9a-f]{6})$/i';