Table of Contents:
PHP Regular Expressions (Regex) – Complete Tutorial with Examples
Welcome to phponline.in – your one-stop hub for mastering PHP programming.
In this detailed course page, we will cover PHP Regular Expressions (Regex) step by step.
Regular Expressions (often called Regex) are powerful tools used to search, match, validate, and manipulate strings. Whether you are building a form validation system, email checker, or search engine, mastering regex in PHP is a must.
By the end of this guide, you will:
- Understand what regular expressions are
- Learn about Regex syntax and metacharacters
- Work with preg_match, preg_match_all, preg_replace, preg_split
- Validate inputs like email, phone, and passwords
- Build real-world projects using regex
- Discover advanced regex techniques for complex matching
What You will Learn
- What are Regular Expressions?
- Why Use Regex in PHP?
- Regex Support in PHP
- Regex Syntax Basics
- Regex Metacharacters Explained
- Regex Quantifiers
- Regex Character Classes
- Anchors in Regex
- Groups and Alternation
- Escaping Special Characters
- PHP Regex Functions Overview
- Using preg_match()
- Using preg_match_all()
- Using preg_replace()
- Using preg_split()
- Validating Email with Regex
- Validating Phone Numbers with Regex
- Validating Passwords with Regex
- Extracting Data from Strings
- Regex with $_POST Form Data
- Real-World Example: Login Form Validation
- Real-World Example: URL Matching
- Real-World Example: Extracting Hashtags
- Real-World Example: Validating Dates
- Regex and Performance Considerations
- Regex vs. String Functions in PHP
- Best Practices for Regex in PHP
- Common Mistakes with Regex
- Advanced Regex Techniques (Lookaheads, Lookbehinds)
- Tools for Testing Regex
- Regex in Security Applications
- Regex in Data Scraping
- Regex in File Handling
- Regex in PHP Arrays
- Regex in Loops and Conditions
- PHP Regex and Global Variables
- Real-Life Mini Project: Regex-Based Contact Form Validator
- Real-Life Mini Project: PHP Regex URL Extractor
- Regex in Object-Oriented PHP
- Summary & Conclusion
1. What are Regular Expressions?
Regular Expressions are patterns used to match text. They help in:
- Searching strings
- Replacing parts of text
- Validating input fields
- Extracting data
Example:
$pattern = "/php/i";
$text = "I love PHP programming!";
if (preg_match($pattern, $text)) {
echo "Match found!";
}
Output:
Match found!
2. Why Use Regex in PHP?
Regex is used for:
- Form validation (email, phone, password)
- Data scraping from text
- Replacing unwanted words
- Extracting structured data
3. Regex Support in PHP
PHP provides regex support via PCRE (Perl Compatible Regular Expressions).
Main functions:
preg_match()
– find pattern in stringpreg_match_all()
– find all matchespreg_replace()
– replace textpreg_split()
– split string
4. Regex Syntax Basics
- Patterns are enclosed between forward slashes
/.../
- Case-insensitive search uses
i
modifier
Example:
preg_match("/hello/i", "Hello World!");
5. Regex Metacharacters Explained
Some special regex symbols:
.
– any character^
– start of string$
– end of string*
– zero or more+
– one or more?
– zero or one[]
– character class|
– OR
6. Regex Quantifiers
{n}
– exact n times{n,}
– n or more times{n,m}
– between n and m times
Example:
preg_match("/[0-9]{3}/", "My number is 123");
7. Regex Character Classes
[0-9]
– digits[a-z]
– lowercase letters[A-Z]
– uppercase letters\d
– digits\w
– word characters\s
– whitespace
8. Anchors in Regex
^word
– match at startword$
– match at end
9. Groups and Alternation
(abc)
– groupa|b
– OR
10. Escaping Special Characters
Use \
before special characters.
preg_match("/\$100/", "Price is $100");
11. PHP Regex Functions Overview
preg_match()
preg_match_all()
preg_replace()
preg_split()
12. Using preg_match()
if (preg_match("/php/i", "I love PHP")) {
echo "Match!";
}
13. Using preg_match_all()
preg_match_all("/\d+/", "My numbers are 12 and 34", $matches);
print_r($matches);
14. Using preg_replace()
$text = "Hello World!";
echo preg_replace("/World/", "PHP", $text);
15. Using preg_split()
$str = "apple,banana,orange";
$fruits = preg_split("/,/", $str);
print_r($fruits);
16. Validating Email with Regex
$email = "test@example.com";
if (preg_match("/^[\w.-]+@[\w.-]+\.[a-z]{2,}$/i", $email)) {
echo "Valid Email";
}
17. Validating Phone Numbers with Regex
$phone = "9876543210";
if (preg_match("/^[0-9]{10}$/", $phone)) {
echo "Valid Phone";
}
18. Validating Passwords with Regex
Strong password: at least 8 chars, 1 uppercase, 1 number.
$password = "Test1234";
if (preg_match("/^(?=.*[A-Z])(?=.*[0-9]).{8,}$/", $password)) {
echo "Strong Password";
}
19. Extracting Data from Strings
preg_match_all("/\d+/", "Order IDs: 123, 456, 789", $matches);
print_r($matches);
20. Regex with $_POST Form Data
Form validation example:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (preg_match("/^[a-zA-Z ]+$/", $_POST['name'])) {
echo "Valid Name";
} else {
echo "Invalid Name";
}
}
21. Real-World Example: Login Form Validation
Validate username and password.
22. Real-World Example: URL Matching
$url = "https://phponline.in";
if (preg_match("/^https?:\/\/[a-z0-9.-]+\.[a-z]{2,}$/i", $url)) {
echo "Valid URL";
}
23. Real-World Example: Extracting Hashtags
$text = "Learning #PHP and #Regex";
preg_match_all("/#(\w+)/", $text, $matches);
print_r($matches[1]);
24. Real-World Example: Validating Dates
$date = "2025-08-18";
if (preg_match("/^\d{4}-\d{2}-\d{2}$/", $date)) {
echo "Valid Date";
}
25. Regex and Performance Considerations
- Complex regex may slow execution
- Use specific patterns for efficiency
26. Regex vs. String Functions in PHP
- Regex = flexible and powerful
- String functions = faster for simple tasks
27. Best Practices for Regex in PHP
- Use anchors
^
and$
- Test regex with tools
- Keep patterns readable
28. Common Mistakes with Regex
- Forgetting escape characters
- Overusing greedy quantifiers
29. Advanced Regex Techniques
- Lookahead:
(?=...)
- Lookbehind:
(?<=...)
- Non-capturing groups:
(?:...)
30. Tools for Testing Regex
- regex101.com
- phpliveregex
31. Regex in Security Applications
- Prevent SQL injection
- Validate inputs before DB insert
32. Regex in Data Scraping
Extract emails, phone numbers from text files.
33. Regex in File Handling
Rename files based on patterns.
34. Regex in PHP Arrays
Filter array values with regex.
35. Regex in Loops and Conditions
Use regex inside loops for filtering datasets.
36. PHP Regex and Global Variables
Regex with $_GET
, $_POST
, and $_SERVER
.
37. Mini Project: Regex-Based Contact Form Validator
Validate name, email, and phone.
38. Mini Project: PHP Regex URL Extractor
Extract all URLs from a web page.
39. Regex in Object-Oriented PHP
Encapsulate regex logic inside classes.
PHP regular expressions, PHP regex tutorial, PHP preg_match, PHP preg_replace, PHP regex examples, PHP regex functions, PHP pattern matching, regex in PHP
Summary & Conclusion
- Regex is essential for validation and text processing
- PHP provides preg_ functions for regex operations
- Real-world apps: validation, scraping, security
Frequently Asked Questions (FAQ)
Q1: What is regex in PHP?
A: Regex is a pattern-matching technique used for string validation and manipulation.
Q2: Which PHP functions use regex?
A: preg_match, preg_match_all, preg_replace, preg_split.
Q3: Is regex faster than string functions?
A: For simple tasks, string functions are faster. Regex is better for complex patterns.
Q4: How to validate email in PHP using regex?
A: Use preg_match("/^[\w.-]+@[\w.-]+\.[a-z]{2,}$/i", $email)
.
Q5: Can regex prevent security attacks?
A: Regex helps sanitize input, reducing XSS and SQL injection risks.