Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * Match the subject using the regex and return the matched capturing groups.
  5. *
  6. * Capturing groups that are not matched are returned as null.
  7. *
  8. * @param string $regex The pattern to search for, as a string.
  9. * @param string $subject The input string.
  10. * @param bool $collapse Return a 1D array instead of a 2D array if there is only
  11. * a single capturing group.
  12. *
  13. * @return array An array containing each set of matches.
  14. *
  15. * @throws \Exception
  16. */
  17. function regex_match_all(string $regex, string $subject, bool $collapse = true): array
  18. {
  19. $status = preg_match_all($regex, $subject, $matches, PREG_UNMATCHED_AS_NULL);
  20. if ($status === 0)
  21. {
  22. return [];
  23. }
  24.  
  25. if ($status === false)
  26. {
  27. throw new Exception('Error matching pattern');
  28. }
  29.  
  30. // Collapse if the matches only contain the full pattern matches and
  31. // the matches of a single capturing group.
  32. if ($collapse && count($matches) === 2)
  33. {
  34. return $matches[1];
  35. }
  36.  
  37. // Exclude full matches from result.
  38. array_splice($matches, 0, 1);
  39.  
  40. // Transpose the matches so that $result[0] is an array of the first set of matches,
  41. // $result[1] is the second set of matches, and so on. preg_match_all has a flag to
  42. // do this automatically but this will exclude unmatched groups from the result.
  43. // This won't make it possible to reliably detect if the result can be collapsed.
  44. $result = [];
  45. foreach ($matches as $key => $group)
  46. {
  47. foreach ($group as $index => $match)
  48. {
  49. $result[$index][$key] = $match;
  50. }
  51. }
  52.  
  53. return $result;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement