Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Match the subject using the regex and return the matched capturing groups.
- *
- * Capturing groups that are not matched are returned as null.
- *
- * @param string $regex The pattern to search for, as a string.
- * @param string $subject The input string.
- * @param bool $collapse Return a 1D array instead of a 2D array if there is only
- * a single capturing group.
- *
- * @return array An array containing each set of matches.
- *
- * @throws \Exception
- */
- function regex_match_all(string $regex, string $subject, bool $collapse = true): array
- {
- $status = preg_match_all($regex, $subject, $matches, PREG_UNMATCHED_AS_NULL);
- if ($status === 0)
- {
- return [];
- }
- if ($status === false)
- {
- throw new Exception('Error matching pattern');
- }
- // Collapse if the matches only contain the full pattern matches and
- // the matches of a single capturing group.
- if ($collapse && count($matches) === 2)
- {
- return $matches[1];
- }
- // Exclude full matches from result.
- array_splice($matches, 0, 1);
- // Transpose the matches so that $result[0] is an array of the first set of matches,
- // $result[1] is the second set of matches, and so on. preg_match_all has a flag to
- // do this automatically but this will exclude unmatched groups from the result.
- // This won't make it possible to reliably detect if the result can be collapsed.
- $result = [];
- foreach ($matches as $key => $group)
- {
- foreach ($group as $index => $match)
- {
- $result[$index][$key] = $match;
- }
- }
- return $result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement