PHP — Regex
Basic pattern matching
<?php
$email = "alice@example.com";
// preg_match
if (preg_match("/^[\w.]+@[\w.]+\.\w+$/", $email)) {
echo "Valid email";
}
// preg_match_all
$text = "Call 123-456-7890 or 987-654-3210";
preg_match_all("/\d{3}-\d{3}-\d{4}/", $text, $matches);
print_r($matches[0]); // [123-456-7890, 987-654-3210]
?>
Pattern syntax
<?php
// Character classes
preg_match("/[aeiou]/", "hello"); // vowel
preg_match("/[^0-9]/", "abc"); // not digit
// Quantifiers
preg_match("/a{3}/", "aaa"); // exactly 3
preg_match("/a{2,}/", "aaaa"); // 2 or more
// Anchors
preg_match("/^hello/", "hello world"); // start
preg_match("/world$/", "hello world"); // end
// Groups
preg_match("/(\d+)-(\d+)/", "123-456", $matches);
echo $matches[1]; // 123
?>
Replacing
<?php
// preg_replace
$s = "Hello, World!";
echo preg_replace("/world/i", "PHP", $s); // Hello, PHP!
// With callback
echo preg_replace_callback("/\d+/", function($matches) {
return $matches[0] * 2;
}, "10 + 20 = 30"); // 20 + 40 = 60
?>
Splitting
<?php
// preg_split
$fields = preg_split("/\s+/", "hello world foo");
print_r($fields); // [hello, world, foo]
?>
Mini Practice
Write PHP code that:
- Validates an email with regex
- Extracts phone numbers from text
- Replaces patterns with preg_replace
- Splits a string with regex
Up Next
In the next lesson, you'll learn about Date Functions — working with dates.
Related Topics
Frequently Asked Questions about Regex
What is Regex in PHP?
Regex is a fundamental concept in PHP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Regex?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Regex.
Why is Regex important in PHP?
Regex is essential for PHP development. Understanding this concept will help you write better code and solve real-world problems more effectively.