Skip to content

Commit 8015d13

Browse files
committed
Strings::replace() added parameters $captureOffset, $unmatchedAsNull
1 parent fd0a5c0 commit 8015d13

File tree

2 files changed

+6
-1
lines changed

2 files changed

+6
-1
lines changed

src/Utils/Strings.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -539,12 +539,15 @@ public static function replace(
539539
string|array $pattern,
540540
string|callable $replacement = '',
541541
int $limit = -1,
542+
bool $captureOffset = false,
543+
bool $unmatchedAsNull = false,
542544
): string {
543545
if (is_object($replacement) || is_array($replacement)) {
544546
if (!is_callable($replacement, false, $textual)) {
545547
throw new Nette\InvalidStateException("Callback '$textual' is not callable.");
546548
}
547-
return self::pcre('preg_replace_callback', [$pattern, $replacement, $subject, $limit]);
549+
$flags = ($captureOffset ? PREG_OFFSET_CAPTURE : 0) | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0);
550+
return self::pcre('preg_replace_callback', [$pattern, $replacement, $subject, $limit, 0, $flags]);
548551

549552
} elseif (is_array($pattern) && is_string(key($pattern))) {
550553
$replacement = array_values($pattern);

tests/Utils/Strings.replace().phpt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,5 @@ 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+
Assert::same('hell0o worl9d!', Strings::replace('hello world!', '#[e-l]+#', fn($m) => implode($m[0]), captureOffset: true));
38+
Strings::replace('hello world!', '#e(x)*#', fn($m) => Assert::null($m[1]), unmatchedAsNull: true);

0 commit comments

Comments
 (0)