Regular Expression
Umar Balarabe
Regular Expression
• Regular expressions (or "regex") are patterns used to match and
manipulate text. They are a powerful tool for tasks like:
Validating user input
Searching and replacing text
Parsing and extracting data
Basic Syntax
• Regular expressions are enclosed in forward slashes `/` and consist of
a pattern of characters and special symbols
Example: `/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/`
Special Characters
• -`.` - Matches any character except newline
• `\d` - Matches any digit character
• `\w` - Matches any word character (letter, digit, or underscore)
• `\s` - Matches any whitespace character
• `^` - Matches the start of the string
• `$` - Matches the end of the string
Character Classes
• `[abc]` - Matches any character in the set (a, b, or c)
• `[^abc]` - Matches any character not in the set
• `[a-z]` - Matches any character in the range (a to z)
Email cont..
• if (preg_match( '/^[a-zA-Z0-9.%_+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/',
$email) ) {
echo "Valid email";
}
Email Validation
• The following regex checks that the input is a valid
email address: `/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.
[a-zA-Z]{2,}$/`
• It validates the username, domain, and top-level
domain
Sources
• Regex101 ([Link] Online regex tester and debugger
• [Link] ([Link]
Comprehensive regex tutorial
• The Complete Regex Course ([Link]
complete-regex-course/