← Back to Chapters

PHP Regular Expressions Tutorial

? PHP Regular Expressions Tutorial

? Quick Overview

PHP supports regular expressions (regex), which are patterns used to match character combinations in strings. Regular expressions are powerful tools for searching and manipulating text, validating inputs, and performing complex search and replace operations.

? Key Concepts

  • preg_match() – Finds the first match of a pattern
  • preg_match_all() – Finds all matches
  • preg_replace() – Replaces matching patterns
  • preg_split() – Splits strings using regex

? Syntax / Theory

PHP regex functions use Perl Compatible Regular Expressions (PCRE). Patterns are enclosed within delimiters like /pattern/ and can include modifiers such as i for case-insensitive matching.

? Code Example

? View Code Example
// Search for a price pattern using preg_match()
<?php
$text = "The price of the item is $20.";
$pattern = "/\$\d+/";

if (preg_match($pattern, $text, $matches)) {
    echo "Found price: " . $matches[0] . "<br>";
} else {
    echo "No price found.<br>";
}
?>

?️ Live Output / Explanation

Output

Found price: $20

The regex /\$\d+/ matches a dollar sign followed by one or more digits.

 

? Interactive Explanation

Try modifying the pattern to detect emails or phone numbers. Regular expressions allow flexible pattern matching without complex logic.

? Use Cases

  • Validating emails, phone numbers, and passwords
  • Extracting specific data from text
  • Sanitizing and cleaning user input
  • Search and replace operations

✅ Tips & Best Practices

  • Use regex testers to validate patterns before coding
  • Keep patterns readable and simple
  • Escape special characters properly
  • Prefer preg_match_all() when multiple matches are needed

? Try It Yourself

  • Write a regex to validate an email address
  • Extract all numbers from a string
  • Use preg_replace() to remove special characters
  • Split a sentence into words using preg_split()