Web Analytics

PHP Regular Expressions

Advanced~25 min read

Regular expressions (regex) are powerful patterns for matching and manipulating text. Perfect for validation, search, and data extraction!

Output
Click Run to execute your code

preg_match - Find Match

<?php
$text = "My email is [email protected]";
if (preg_match('/[\w\.-]+@[\w\.-]+\.\w+/', $text, $matches)) {
    echo "Email: " . $matches[0];
}
?>

preg_replace - Replace Pattern

<?php
$text = "Hello World";
$result = preg_replace('/World/', 'PHP', $text);
echo $result; // Hello PHP
?>

Common Patterns

<?php
$patterns = [
    'email' => '/^[\w\.-]+@[\w\.-]+\.\w+$/',
    'phone' => '/^\d{3}-\d{3}-\d{4}$/',
    'url' => '/^https?:\/\/[\w\.-]+\.\w+/',
];
?>

Summary

  • preg_match(): Find first match
  • preg_match_all(): Find all matches
  • preg_replace(): Replace patterns
  • Use case: Validation, search, extraction

What's Next?

Next, learn about Date & Time - working with dates and timezones!