RegEx

Regular expressions (regex) are patterns used to search, match, replace and/or validate text.

In PHP, regex is most commonly used to:

  • Check if a string contains something
  • Validate simple formats (email, username, keywords)
  • Search or extract parts of a string

Regex in PHP is handled using functions like preg_match() and preg_match_all().


Basic Regex Syntax in PHP

A regular expression is written as a string with delimiters, a pattern, and optional modifiers:

/pattern/modifiers

Example:

/@/
  • / – delimiter
  • @ – pattern to search for
  • no modifiers used

preg_match() in Practice

preg_match('/@/', $email);
  • Returns 1 if the pattern is found
  • Returns 0 if the pattern is not found

This makes it useful for simple checks, not full validation.


Common Beginner Patterns

  • /@/ – checks if @ exists
  • /[0-9]/ – checks if the string contains a digit
  • /[a-z]/i – checks for letters (case-insensitive)
  • /^Hello/ – checks if string starts with “Hello”
  • /World$/ – checks if string ends with “World”

Modifiers (Simple Ones)

  • i – case-insensitive match
    Example:/php/i

Important Notes

  • Regex checks patterns, not meaning
    Finding @ does not mean something is a valid email, only that it looks like one.
  • Regex is often used as a first filter, not final validation.
  • Real-world applications usually combine regex with other validation logic.

Mental Model to Keep

Think of regex as:

“A search rule for text”

Not magic. Not parsing logic yet. Just pattern matching.