HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Regular Expressions

Regular expressions (often called Regex) are sequences of characters that form a search pattern. They are used for complex string searching, validation (like emails), and advanced text manipulation.


1. What is Regex?

A pattern can consist of a single character, or a more complicated template. Patterns are usually enclosed in delimiters, like forward slashes /.

Example pattern: /redohub/i (The i makes the search case-insensitive).


2. Regex Functions in PHP

PHP uses the PCRE (Perl Compatible Regular Expressions) syntax. These are the most common functions:

Search for Match - preg_match()

Checks if a pattern exists in a string. Returns 1 if found, 0 if not.

<?php
    $str = "Visit RedoHub";
    $pattern = "/redohub/i";
    echo preg_match($pattern, $str); // Output: 1
?>

Find All Matches - preg_match_all()

Returns the number of times a pattern was found in the string.

<?php
    $str = "The rain in SPAIN falls mainly on the plains.";
    $pattern = "/ain/i";
    echo preg_match_all($pattern, $str); // Output: 4
?>

Find and Replace - preg_replace()

Replaces matches with a new string.

<?php
    $str = "Visit Microsoft!";
    $pattern = "/microsoft/i";
    echo preg_replace($pattern, "RedoHub", $str); // Output: Visit RedoHub!
?>

3. Basic Regex Modifiers

Modifier Description
iPerforms a case-insensitive search.
mPerforms a multiline search.
uEnables correct matching of UTF-8 encoded characters.
Safety First: Regex is extremely powerful but can be slow if patterns are poorly written. For simple searches, use strpos() or str_replace() as they are much faster.
Common Pattern: Use /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/ for basic email validation.

Key Takeaways

  • Use delimiters like / to wrap your pattern.
  • Modifers change the behavior of the search (e.g., i for case-insensitive).
  • Use preg_match() for existence checks.
  • Use preg_replace() for complex pattern-based swaps.
  • Always test your regex patterns with online tools before implementing!