W3docs

preg_match_all()

In PHP, regular expressions are an essential tool for manipulating and searching strings. The preg_match_all() function is one of the many functions that PHP

Introduction

In PHP, regular expressions are essential for searching and manipulating strings. The preg_match_all() function searches a subject string for all occurrences of a pattern and returns the total number of matches. This article explains how to use it effectively.

Understanding the preg_match_all() function

The preg_match_all() function searches a subject string for all occurrences of a regular expression pattern. It returns the number of matches found (or false on error) and populates the $matches array. The syntax is:

preg_match_all($pattern, $subject, &$matches, $flags = 0, $offset = 0);
  • $pattern: The regular expression pattern.
  • $subject: The string to search.
  • $matches: An array filled with the matches found.
  • $flags: Optional. Modifies search behavior. Common flags include PREG_PATTERN_ORDER (default, groups results by pattern) and PREG_SET_ORDER (groups results by occurrence). PREG_OFFSET_CAPTURE adds the byte offset of each match.
  • $offset: Optional. Specifies the starting position in the subject string.

Example Usage

The following example demonstrates capturing groups and how the $matches array is structured:

<?php

$pattern = '/([A-Z][a-z]+) (\d+)/';
$subject = 'Alice 25 Bob 30';

preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);

foreach ($matches as $match) {
  echo "Name: {$match[1]}, Age: {$match[2]}\n";
}

In this example, the pattern uses capturing groups () to extract names and ages. With PREG_SET_ORDER, $matches is indexed by match occurrence, so $match[0] contains the full match, $match[1] contains the first group (name), and $match[2] contains the second group (age). Without capturing groups, $matches[0] holds all full matches, and no additional group indices are created.

Conclusion

The preg_match_all() function is essential for finding all pattern matches in PHP strings. It allows developers to efficiently extract and manipulate data. This overview covers its core usage and array structure. For further questions, refer to the official PHP documentation.

Practice

Practice

What is the purpose of the preg_match_all() function in PHP?