📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners Regular Expressions

Regular Expressions

6 min read Quiz at the end
Regular expressions let you search, match, and replace text using patterns. PHP uses preg_match(), preg_replace(), and preg_split() for regex. They are great for validating emails, phone numbers, and complex text patterns.

Regular Expressions

// Test if pattern matches
preg_match('/^\d{3}-\d{4}$/', "555-1234"); // 1 or 0

// Find all matches
preg_match_all('/\d+/', "abc123def456", $m);
print_r($m[0]);  // ["123", "456"]

// Replace matches
preg_replace('/\s+/', ' ', "too   many   spaces");
// "too many spaces"

// Split by pattern
preg_split('/[\s,]+/', "one two,three");
// ["one", "two", "three"]

// Common patterns
'/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/'  // email
'/^\+?[\d\s\-]{10,15}$/'  // phone
'/^(?=.*[A-Z])(?=.*\d).{8,}$/'  // strong password
Topic Quiz · 5 questions

Test your understanding before moving on

1. Which PHP function tests if a regex pattern matches?
💡 preg_match() returns 1 if the pattern matches, 0 if not, false on error.
2. Which function finds all matches in a string?
💡 preg_match_all() finds all occurrences of the pattern.
3. Which function replaces regex matches?
💡 preg_replace() replaces pattern matches with a replacement string.
4. What delimiter is commonly used for PHP regex?
💡 The most common regex delimiters are / or # — e.g., /pattern/ or #pattern#.
5. What does the + quantifier mean in regex?
💡 + means one or more occurrences of the preceding element.