Skip to content

Commit

Permalink
Strings::matchAll() accepts callback
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Aug 7, 2024
1 parent 8675d9b commit e9eba31
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions src/Utils/Strings.php
Original file line number Diff line number Diff line change
Expand Up @@ -594,15 +594,16 @@ public static function matchAll(
string $subject,
#[Language('RegExp')]
string $pattern,
bool|int $captureOffset = false,
int|callable|null $callback = null,
int $offset = 0,
bool $captureOffset = false,
bool $unmatchedAsNull = false,
bool $patternOrder = false,
bool $utf8 = false,
): array
{
$flags = is_int($captureOffset) // back compatibility
? $captureOffset
$flags = is_int($callback) // back compatibility
? $callback
: ($captureOffset ? PREG_OFFSET_CAPTURE : 0) | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0) | ($patternOrder ? PREG_PATTERN_ORDER : 0);

if ($utf8) {
Expand All @@ -614,6 +615,21 @@ public static function matchAll(
return [];
}

if ($callback && !is_int($callback)) {
while (preg_match($pattern, $subject, $m, $flags & PREG_OFFSET_CAPTURE, $offset)) {
if (!$captureOffset) {
$m = array_map(fn($item) => $item[0], $m);
} elseif ($utf8) {
$m = self::bytesToChars($subject, [$m])[0];
}
if ($callback($m) === false) {
break;
}
$offset = $m[0][1] + strlen($m[0][0]);
}
return [];
}

self::pcre('preg_match_all', [
$pattern, $subject, &$m,
($flags & PREG_PATTERN_ORDER) ? $flags : ($flags | PREG_SET_ORDER),
Expand Down

0 comments on commit e9eba31

Please sign in to comment.