PHP Regular Expressions, Types and Usage with Examples
Regular expressions (regex) are patterns used to match and manipulate text. PHP supports regex through two main functions: preg_match() and preg_replace(). These help in validating, searching, and replacing text efficiently.
1. Matching Patterns – preg_match()
Purpose: Checks if a pattern exists in a string.
Returns:
1if a match is found0if no matchfalseon error
Example:
$pattern = "/php/i"; // 'i' makes it case-insensitive
$text = "I love PHP!";
if (preg_match($pattern, $text)) {
echo "Pattern found!";
} else {
echo "No match.";
}
// Outputs: Pattern found!
Use preg_match() to validate emails, phone numbers, or any pattern.
2. Replacing Text – preg_replace()
Purpose: Finds matches and replaces them with a new string.
Returns: Modified string with replacements done.
Example:
$pattern = "/world/i";
$text = "Hello World";
$newText = preg_replace($pattern, "PHP", $text);
echo $newText; // Outputs: Hello PHP
Great for cleaning data or formatting text dynamically.
3. Extracting Multiple Matches – preg_match_all()
Purpose: Finds all matches in a string.
Returns: Number of matches and an array of results.
Example:
$pattern = "/\d+/"; // Matches digits
$text = "Order 123, Code 456, ID 789";
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);
// Outputs: Array ( [0] => 123 [1] => 456 [2] => 789 )
Helpful for extracting numbers or words from long strings.
4. Validating Email Example
$email = "user@example.com";
$pattern = "/^[\w.-]+@[\w.-]+\.\w+$/";
if (preg_match($pattern, $email))
{
echo "Valid email.";
}
else
{
echo "Invalid email.";
}
// Outputs: Valid email.
How to Write a Regular Expression in PHP
Writing a regular expression involves defining a pattern that matches specific text. It starts with choosing delimiters, using character classes, quantifiers, and anchors to capture the desired pattern.
Steps:
- Select delimiters (usually
/). - Use character classes to define allowed characters.
- Add quantifiers to specify repetition.
- Use anchors to limit the position (start or end of a string).
- Apply flags for flexibility (like case-insensitivity).
Common Regex Patterns
| Pattern | Meaning | Example Match |
|---|---|---|
. |
Any single character | a, b, 1 |
^ |
Start of string | ^Hello → "Hello World" |
$ |
End of string | World$ → "Hello World" |
\d |
Any digit (0-9) | 123, 7 |
\w |
Any word character | abc, A1 |
\s |
Whitespace character | space, tab |
* |
Zero or more times | go* → g, go, goo |
+ |
One or more times | go+ → go, goo |
{n} |
Exactly n times | a{3} → aaa |
| | | pattern1 or pattern2 | OR operator |
( ) |
Grouping | (ab)+ → ab, abab |
[abc] |
Any character inside | a, b, or c |
[^abc] |
Not a, b, or c | d, e |
Example of Common Regular Expressions
<?php
// Simple Examples and Usage of Regular Expressions in PHP
// 1. Check if a string contains a specific word
$text = "Welcome to PHP tutorials.";
if (preg_match("/PHP/", $text)) {
echo "'PHP' found in the text.\n"; // Output: 'PHP' found in the text.
}
// 2. Validate an email address format
$email = "example@test.com";
if (preg_match("/^([a-zA-Z0-9_\.-]+)@([a-zA-Z0-9\.-]+)\\.([a-zA-Z]{2,6})$/", $email)) {
echo "Valid email format.\n"; // Output: Valid email format.
}
// 3. Replace digits in a string with '#'
$text = "Order number: 12345";
$result = preg_replace("/\\d/", "#", $text);
echo "$result\n"; // Output: Order number: #####
// 4. Extract all words from a sentence
$sentence = "Hello world, welcome to PHP!";
preg_match_all("/\\b\\w+\\b/", $sentence, $matches);
print_r($matches[0]);
// Output: ['Hello', 'world', 'welcome', 'to', 'PHP']
// 5. Remove extra spaces from a string
$text = "This is spaced text.";
$cleaned = preg_replace("/\\s+", " ", $text);
echo "$cleaned\n"; // Output: This is spaced text.
// 6. Check if a string starts with a specific word
$text = "Hello there!";
if (preg_match("/^Hello/", $text)) {
echo "Starts with 'Hello'.\n"; // Output: Starts with 'Hello'.
}
// 7. Check if a string ends with a specific word
$text = "Goodbye world.";
if (preg_match("/world\\.$/", $text)) {
echo "Ends with 'world.'.\n"; // Output: Ends with 'world.'.
}
// 8. Find numbers with exactly 3 digits
$text = "Numbers: 12, 345, 6789";
preg_match_all("/\\b\\d{3}\\b/", $text, $matches);
print_r($matches[0]);
// Output: ['345']
// 9. Match phone numbers (Format: 123-456-7890)
$phone = "Contact: 123-456-7890";
if (preg_match("/\\b\\d{3}-\\d{3}-\\d{4}\\b/", $phone, $matches)) {
echo "Phone number found: $matches[0]\n"; // Output: Phone number found: 123-456-7890
}
// 10. Replace all non-alphanumeric characters
$text = "Hello! How are you? #2024";
$clean = preg_replace("/[^a-zA-Z0-9 ]/", "", $text);
echo "$clean\n"; // Output: Hello How are you 2024
?>