Regular Expressions Demystified

matt
Matthew Gros · Oct 1, 2025

TLDR

Learn character classes, quantifiers, groups, and anchors. Test with regex101.com. Keep patterns simple.

Regular Expressions Demystified

Regex Isn't That Scary

Learn a few patterns and you're set for most tasks.

Basic Patterns

.        Any character
\d       Digit (0-9)
\w       Word character (a-z, A-Z, 0-9, _)
\s       Whitespace

Quantifiers

*        Zero or more
+        One or more
?        Zero or one
{3}      Exactly 3
{2,5}    Between 2 and 5

Anchors

^        Start of string
$        End of string
\b       Word boundary

Common Examples

// Email (basic)
'/^[\w.-]+@[\w.-]+\.\w+$/'

// Phone (US)
'/^\d{3}-\d{3}-\d{4}$/'

// URL
'/^https?:\/\/[\w.-]+\.\w+/'

// Slug
'/^[a-z0-9]+(?:-[a-z0-9]+)*$/'

Groups and Capture

$pattern = '/(\d{4})-(\d{2})-(\d{2})/';
preg_match($pattern, '2024-01-15', $matches);
// $matches[0] = '2024-01-15'
// $matches[1] = '2024'
// $matches[2] = '01'
// $matches[3] = '15'

// Named groups
$pattern = '/(?<year>\d{4})-(?<month>\d{2})/';
// $matches['year'] = '2024'

Replace

// Simple
$result = preg_replace('/\s+/', ' ', $text); // Collapse whitespace

// With callback
$result = preg_replace_callback(
    '/\b(\w)/',
    fn($m) => strtoupper($m[1]),
    'hello world'
); // "Hello World"

Testing

Use regex101.com to:

  • Build patterns interactively
  • See matches highlighted
  • Understand what each part does

About the Author

matt

I build and ship automation-driven products using Laravel and modern frontend stacks (Vue/React), with a focus on scalability, measurable outcomes, and tight user experience. I’m based in Toronto, have 13+ years in PHP, and I also hold a pilot’s license. I enjoy working on new tech projects and generally exploring new technology.