Skip to content

Commit c330f89

Browse files
committed
Strings::replace() added parameters $captureOffset, $unmatchedAsNull
1 parent 9c0c26c commit c330f89

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
@@ -517,12 +517,15 @@ public static function replace(
517517
string|array $pattern,
518518
string|callable $replacement = '',
519519
int $limit = -1,
520+
bool $captureOffset = false,
521+
bool $unmatchedAsNull = false,
520522
): string {
521523
if (is_object($replacement) || is_array($replacement)) {
522524
if (!is_callable($replacement, false, $textual)) {
523525
throw new Nette\InvalidStateException("Callback '$textual' is not callable.");
524526
}
525-
return self::pcre('preg_replace_callback', [$pattern, $replacement, $subject, $limit]);
527+
$flags = ($captureOffset ? PREG_OFFSET_CAPTURE : 0) | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0);
528+
return self::pcre('preg_replace_callback', [$pattern, $replacement, $subject, $limit, 0, $flags]);
526529

527530
} elseif (is_array($pattern) && is_string(key($pattern))) {
528531
$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)