PHP RegEx
Regular expressions describe patterns used to search and validate text.
What is it?
Regular expressions describe patterns used to search and validate text.
Why do we use it?
Regex is useful for usernames, IDs, phone numbers and custom text formats.
How does it work?
A pattern is compared with a subject string using PHP regular-expression functions.
Syntax
$pattern = "/^[A-Za-z0-9]+$/";
Example
<?php
$text = "AIFA123";
$pattern = "/^[A-Za-z0-9]+$/";
if (preg_match($pattern, $text)) {
echo "Valid";
} else {
echo "Invalid";
}
?>
Example Explained
More Examples
<?php $phone = "9876543210"; if (preg_match("/^[0-9]{10}$/", $phone)) echo "Valid Phone"; ?>
⚠️ Important Rules
Test regex patterns carefully with valid and invalid input.
❌ Common Mistakes
Missing delimiters or creating an overly broad pattern.
🌍 Real-World Use
Form validation and text processing.
📝 Practice Exercise
Create a regex that validates a ten-digit phone number.
💻 Try It Yourself
Write and run this PHP lesson inside the AIFA Coding Lab.