PHP Tutorial

PHP Flow Control

PHP Functions

PHP String

PHP Array

PHP Date Time

PHP Object Oriented

Regular Expression

PHP Cookie & Session

PHP Error & Exception handling

MySQL in PHP

PHP File Directory

PHP Image Processing

PHP preg_match_all(): Perform Global Regular Expression Matching

The preg_match_all() function in PHP is used to perform a global regular expression match. It's similar to preg_match(), but it continues searching the string until it can't find more matches.

Here's a basic tutorial on how to use the preg_match_all() function in PHP:

Syntax:

The syntax of preg_match_all() is:

preg_match_all(string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] ) : int|false
  • $pattern: The pattern to search for, as a string.
  • $subject: The input string.
  • &$matches: If provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.
  • $flags: It could be PREG_PATTERN_ORDER, PREG_SET_ORDER, PREG_OFFSET_CAPTURE. PREG_PATTERN_ORDER orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parentheses, and so on. PREG_SET_ORDER orders results with first set of matches first.
  • $offset: Normally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search.

Return Value:

Returns the number of full pattern matches (which might be zero), or FALSE if an error occurred.

Example:

Here's an example demonstrating how to use preg_match_all():

<?php
    $pattern = '/foo/';
    $subject = "foo bar foo baz";

    // using preg_match_all()
    if (preg_match_all($pattern, $subject, $matches)) {
        echo "Matches found: " . count($matches[0]);
    } else {
        echo "No matches found.";
    }
?>

In this example, the $pattern is a regular expression that matches the string 'foo'. The preg_match_all() function then checks if the pattern exists in the $subject string and if it does, it outputs the count of matches. If the pattern does not exist in the string, it outputs "No matches found.".

You can use PREG_SET_ORDER to get a different structure in the $matches array:

<?php
    $pattern = '/(foo)(bar)/';
    $subject = "foobar foobar";

    // using preg_match_all() with PREG_SET_ORDER
    preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);

    // Output: Array ( [0] => Array ( [0] => foobar [1] => foo [2] => bar ) [1] => Array ( [0] => foobar [1] => foo [2] => bar ) )
    print_r($matches);
?>

In this example, the $pattern is a regular expression that matches the string 'foobar' with two groups, one for 'foo' and one for 'bar'. The preg_match_all() function then checks if the pattern exists in the $subject string and fills the $matches array with the matches in the order they appear in the input.

  1. Global regular expression matching with preg_match_all() in PHP:

    • preg_match_all() is used to perform global regular expression matching against a string.
    $pattern = "/apple/";
    $text = "I have an apple and another apple.";
    
    if (preg_match_all($pattern, $text, $matches)) {
        echo "Number of matches: " . count($matches[0]);
    } else {
        echo "No matches found.";
    }
    
  2. Extracting and capturing all matches with preg_match_all() in PHP:

    • Use capturing groups to extract all matches.
    $pattern = "/(\d{2})-(\d{2})-(\d{4})/";
    $dateString = "12-25-2022 and 01-01-2023";
    
    if (preg_match_all($pattern, $dateString, $matches)) {
        $dates = [];
        for ($i = 0; $i < count($matches[0]); $i++) {
            $day = $matches[1][$i];
            $month = $matches[2][$i];
            $year = $matches[3][$i];
            $dates[] = "$month/$day/$year";
        }
        echo "Dates: " . implode(", ", $dates);
    }
    
  3. Case-insensitive matching in PHP preg_match_all():

    • Use the i flag for case-insensitive matching.
    $pattern = "/apple/i";
    $text = "I have an Apple and another apple.";
    
    if (preg_match_all($pattern, $text, $matches)) {
        echo "Number of matches: " . count($matches[0]);
    } else {
        echo "No matches found.";
    }
    
  4. Returning the number of total matches with preg_match_all() in PHP:

    • Check the number of total matches using count($matches[0]).
    $pattern = "/apple/";
    $text = "I have an apple and another apple.";
    
    if (preg_match_all($pattern, $text, $matches)) {
        echo "Number of matches: " . count($matches[0]);
    } else {
        echo "No matches found.";
    }
    
  5. Using preg_match_all() for pattern validation in PHP:

    • Validate input patterns using preg_match_all().
    $pattern = "/^[a-zA-Z0-9_]+$/";
    $username = "user123";
    
    if (preg_match_all($pattern, $username, $matches)) {
        echo "Valid username!";
    } else {
        echo "Invalid username.";
    }
    
  6. Handling multiple patterns with preg_match_all() in PHP:

    • Use the | (pipe) symbol for OR conditions.
    $patterns = ["/apple/", "/orange/"];
    $text = "I have an orange.";
    
    if (preg_match_all($patterns, $text, $matches)) {
        echo "Number of matches: " . count($matches[0]);
    } else {
        echo "No matches found.";
    }
    
  7. Error handling and debugging with preg_match_all() in PHP:

    • Check for errors using preg_last_error().
    $pattern = "/[a-z/";
    $text = "Invalid pattern";
    
    if (preg_match_all($pattern, $text, $matches)) {
        echo "Number of matches: " . count($matches[0]);
    } else {
        $error = preg_last_error();
        echo "Error: $error";
    }