Skip to content

Commit d2d0724

Browse files
committed
Strings::replace() added parameters $captureOffset, $unmatchedAsNull
1 parent 4291967 commit d2d0724

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

src/Utils/Strings.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -556,13 +556,16 @@ public static function replace(
556556
string|array $pattern,
557557
string|callable $replacement = '',
558558
int $limit = -1,
559+
bool $captureOffset = false,
560+
bool $unmatchedAsNull = false,
559561
): string {
560562
if (is_object($replacement) || is_array($replacement)) {
561563
if (!is_callable($replacement, false, $textual)) {
562564
throw new Nette\InvalidStateException("Callback '$textual' is not callable.");
563565
}
564566

565-
return self::pcre('preg_replace_callback', [$pattern, $replacement, $subject, $limit]);
567+
$flags = ($captureOffset ? PREG_OFFSET_CAPTURE : 0) | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0);
568+
return self::pcre('preg_replace_callback', [$pattern, $replacement, $subject, $limit, 0, $flags]);
566569

567570
} elseif (is_array($pattern) && is_string(key($pattern))) {
568571
$replacement = array_values($pattern);

tests/Utils/Strings.replace().phpt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,7 @@ Assert::same('#@ @@@#d!', Strings::replace('hello world!', [
3434
]));
3535
Assert::same(' !', Strings::replace('hello world!', '#\w#'));
3636
Assert::same(' !', Strings::replace('hello world!', ['#\w#']));
37+
38+
// flags & callback
39+
Assert::same('hell0o worl9d!', Strings::replace('hello world!', '#[e-l]+#', fn($m) => implode('', $m[0]), captureOffset: true));
40+
Strings::replace('hello world!', '#e(x)*#', fn($m) => Assert::null($m[1]), unmatchedAsNull: true);

0 commit comments

Comments
 (0)