What is it?
A regular expression (regex) is a pattern that describes a set of strings. PHP uses PCRE regex via preg_ functions for searching, validating, and replacing text based on patterns.
Why does it matter?
Regex solves in one line what would take 20 lines of string functions — validating phone numbers, extracting data from HTML, sanitizing URLs, or replacing patterns across large text.
An introduction to PHP regex — preg_match, preg_replace, capturing groups, and validation patterns.
Real-World Use Cases
- ✅ Form validation - Validate Indian mobile numbers (must start with 6-9, exactly 10 digits) with a single preg_match pattern.
- 🔗 URL slug generation - Use preg_replace to convert any title into a URL-safe slug by replacing non-alphanumeric characters with hyphens.
- 📧 Email domain filtering - Extract the domain from an email using a capturing group to enforce company-only signups.
- 🧹 Data cleaning - Strip all HTML tags from user input, remove extra whitespace, and normalize phone number formats.
preg_match — Test a Pattern
// preg_match — Test a Pattern
$email = "test@example.com";
if (preg_match("/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i", $email)) {
echo "Valid Email";
}
Capturing Groups — Extract Data
// Capturing Groups — Extract Data
$text = "Order ID: 12345";
preg_match("/Order ID: (\d+)/", $text, $matches);
echo $matches[1]; // 12345
preg_replace — Clean and Transform
// preg_replace — Clean and Transform
$phone = "(987)-654-3210";
$clean = preg_replace("/[^0-9]/", "", $phone);
echo $clean; // 9876543210
Q: Should I use regex or filter_var for email validation?
Use filter_var($email, FILTER_VALIDATE_EMAIL) for basic validation — faster and built-in. Use regex only for custom rules like allowing only specific domains.
Comments (0)
No comments yet. Be the first!
Leave a Comment