Introduction
Regular expressions (regex) help you search, match, and validate text using patterns in PHP. They are useful for checking email formats, validating mobile numbers, finding digits, replacing unwanted characters, and checking product codes. PHP provides functions such as preg_match(), preg_match_all(), and preg_replace() for working with regular expressions. In this chapter, you will understand the concepts of Regular Expressions with PHP these functions through solved PHP questions using realistic examples.
Question 1: Check Whether a String Contains a Number
Problem Statement
Write a PHP program to check whether the product name "Laptop2026" contains at least one digit using preg_match().
PHP Solution
<?php
$product = "Laptop2026";
if (preg_match("/[0-9]/", $product)) {
echo "The product name contains a number.";
} else {
echo "The product name does not contain a number.";
}
?>
Sample Output
The product name contains a number.
Explanation
The pattern /[0-9]/ matches any single digit from 0 to 9. The preg_match() function returns 1 when a match is found and 0 when no match is found.
Concepts Covered
- Regular expressions
preg_match()- Digit pattern
[0-9]
Question 2: Validate a Username Using Regex
Problem Statement
Check whether the username "Rahul123" contains only letters and digits, with a length between 5 and 12 characters.
PHP Solution
<?php
$username = "Rahul123";
$pattern = "/^[a-zA-Z0-9]{5,12}$/";
if (preg_match($pattern, $username)) {
echo "Valid username.";
} else {
echo "Invalid username.";
}
?>
Sample Output
Valid username.
Explanation
The pattern contains several parts:
^marks the beginning of the string.[a-zA-Z0-9]allows uppercase letters, lowercase letters, and digits.{5,12}requires between 5 and 12 characters.$marks the end of the string.
Together, these rules require the entire username to contain only permitted characters and have the specified length.
Concepts Covered
- Username validation
- Character classes
- Quantifiers
- Start and end anchors
Question 3: Check Whether an Email Has a Basic Valid Format
Problem Statement
Check whether "student@example.com" matches a basic email pattern using preg_match().
PHP Solution
<?php
$email = "student@example.com";
$pattern = "/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/";
if (preg_match($pattern, $email)) {
echo "Email format looks valid.";
} else {
echo "Invalid email format.";
}
?>
Sample Output
Email format looks valid.
Explanation
This pattern checks for a basic email structure:
- A sequence of permitted characters before
@. - An
@symbol. - A domain section.
- A dot followed by at least two letters.
This is only a basic format check. It does not prove that the address exists or can receive email. For application-level validation, PHP also provides filter_var() with FILTER_VALIDATE_EMAIL.
Concepts Covered
- Email format checking
preg_match()- Escaping special characters with
\. - Basic input validation
Question 4: Validate a 10-Digit Mobile Number
Problem Statement
Check whether "9876543210" contains exactly 10 digits.
PHP Solution
<?php
$mobile = "9876543210";
$pattern = "/^[0-9]{10}$/";
if (preg_match($pattern, $mobile)) {
echo "Mobile number has exactly 10 digits.";
} else {
echo "Invalid mobile number format.";
}
?>
Sample Output
Mobile number has exactly 10 digits.
Explanation
The pattern [0-9]{10} requires exactly 10 digits. The ^ and $ anchors ensure that the entire string consists of those 10 digits, without additional characters.
This checks the format only, not whether the number is assigned or active.
Concepts Covered
- Numeric input validation
- Exact character counts
preg_match()- Regex anchors
Question 5: Extract All Numbers From a String
Problem Statement
Extract all numbers from the string "Laptop price 45000, Mouse price 800" using preg_match_all().
PHP Solution
<?php
$text = "Laptop price 45000, Mouse price 800";
preg_match_all("/[0-9]+/", $text, $matches);
print_r($matches[0]);
?>
Sample Output
Array
(
[0] => 45000
[1] => 800
)
Explanation
The pattern [0-9]+ matches one or more consecutive digits. The preg_match_all() function finds every match and stores the results in the $matches array.
The first result array, $matches[0], contains all complete matches.
Concepts Covered
preg_match_all()- Extracting digits
- The
+quantifier - Arrays of regex matches
Question 6: Replace Spaces With Hyphens
Problem Statement
Convert the text "PHP Regular Expressions" into "PHP-Regular-Expressions" using preg_replace().
PHP Solution
<?php
$text = "PHP Regular Expressions";
$result = preg_replace("/\s+/", "-", $text);
echo $result;
?>
Sample Output
PHP-Regular-Expressions
Explanation
The pattern \s+ matches one or more whitespace characters, including spaces and tabs. The preg_replace() function replaces each matching sequence with a hyphen.
Concepts Covered
preg_replace()- Whitespace pattern
\s - The
+quantifier - Replacing text
Question 7: Remove All Non-Digit Characters
Problem Statement
A company stores a contact number as "+91-98765-43210". Remove all characters except digits.
PHP Solution
<?php
$mobile = "+91-98765-43210";
$result = preg_replace("/[^0-9]/", "", $mobile);
echo $result;
?>
Sample Output
919876543210
Explanation
The pattern [^0-9] matches any character that is not a digit. The preg_replace() function replaces each such character with an empty string, removing it.
This example removes the plus sign and hyphens, leaving only the digits.
Concepts Covered
preg_replace()- Negated character classes
- Removing unwanted characters
- Cleaning text data
Question 8: Check Whether a Product Code Follows a Pattern
Problem Statement
A company uses product codes such as "PRD-2026-105". Check whether the code follows the format PRD-YYYY-NNN, where YYYY represents four digits and NNN represents three digits.
PHP Solution
<?php
$productCode = "PRD-2026-105";
$pattern = "/^PRD-[0-9]{4}-[0-9]{3}$/";
if (preg_match($pattern, $productCode)) {
echo "Valid product code.";
} else {
echo "Invalid product code.";
}
?>
Sample Output
Valid product code.
Explanation
The pattern checks the entire product code:
PRD-requires the exact prefix.[0-9]{4}requires four digits.- The next hyphen must be present.
[0-9]{3}requires three digits.^and$ensure the complete string follows the pattern.
Concepts Covered
- Product code validation
- Regex quantifiers
- Fixed text patterns
preg_match()
Question 9: Replace Multiple Spaces With a Single Space
Problem Statement
Clean the text "PHP is easy" by replacing multiple consecutive spaces with one space.
PHP Solution
<?php
$text = "PHP is easy";
$result = preg_replace("/ {2,}/", " ", $text);
echo $result;
?>
Sample Output
PHP is easy
Explanation
The pattern {2,} matches two or more consecutive ordinary space characters. The replacement " " changes each matching sequence into a single space.
This pattern targets spaces specifically. If you also need to handle tabs and other whitespace characters, use /\s+/ instead.
Concepts Covered
preg_replace()- Space matching
- Quantifier
{2,} - Text cleanup
Question 10: Extract an Employee ID From a Record
Problem Statement
An employee record contains the text "Name: Neha Sharma, Employee ID: EMP125". Extract the employee ID using preg_match() and a capturing group.
PHP Solution
<?php
$record = "Name: Neha Sharma, Employee ID: EMP125";
$pattern = "/Employee ID:\s*(EMP[0-9]+)/";
if (preg_match($pattern, $record, $matches)) {
echo "Employee ID: " . $matches[1];
} else {
echo "Employee ID not found.";
}
?>
Sample Output
Employee ID: EMP125
Explanation
The pattern searches for the text Employee ID: followed by optional whitespace and an ID beginning with EMP, followed by one or more digits.
The parentheses around (EMP[0-9]+) create a capturing group. PHP stores the full match in $matches[0] and the captured employee ID in $matches[1].
Concepts Covered
preg_match()- Capturing groups
- Extracting structured data
- Employee record processing
Key Takeaways
- Regular expressions define patterns for searching, matching, and replacing text.
preg_match()checks for a match and returns whether one was found.preg_match_all()finds all occurrences of a pattern.preg_replace()replaces matching text with a new value.[0-9]matches a digit, while[a-zA-Z]matches English letters.+means one or more occurrences;{5,12}specifies a permitted range.^and$anchor a pattern to the beginning and end of the string.\smatches whitespace, and[^0-9]matches any non-digit character.- Parentheses create capturing groups that can be accessed through the
$matchesarray. - Regex checks formats, but they do not automatically verify that an email address or mobile number actually exists.
Frequently Asked Questions
1. What is a regular expression in PHP?
A regular expression, or regex, is a pattern used to search, match, validate, or replace text.
2. Which function checks a regex pattern in PHP?
preg_match() checks whether a string contains a match for a regular expression.
3. What is the difference between preg_match() and preg_match_all()?
preg_match() returns the first match, while preg_match_all() finds all matches in the string.
4. What is preg_replace() used for?
preg_replace() searches for text matching a regex pattern and replaces it with the specified replacement.
5. What does [0-9] mean in a regex?
[0-9] matches any single digit from zero to nine.
6. What do ^ and $ mean in regular expressions?
^ matches the beginning of the string, and $ matches the end. Together, they can help ensure the entire string follows a pattern.
7. What does the + symbol mean in regex?
The + quantifier means one or more occurrences of the preceding character or pattern.
8. Can regex validate email addresses in PHP?
Regex can check a basic email format, but a pattern alone cannot confirm that an email address exists. PHP’s filter_var() with FILTER_VALIDATE_EMAIL is a useful alternative for basic application-level email validation.
9. Are PHP regular expressions case-sensitive?
By default, PHP’s PCRE regex patterns are case-sensitive. Adding the i modifier, such as /php/i, makes matching case-insensitive.
10. Where are regular expressions used in real PHP projects?
They are commonly used for validating input formats, extracting IDs, cleaning text, checking product codes, and replacing unwanted characters.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
