Skip to content

Commit

Permalink
Strings::replace() added parameters $captureOffset, $unmatchedAsNull
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Oct 27, 2021
1 parent 5c2c477 commit a08d1e4
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/Utils/Strings.php
Original file line number Diff line number Diff line change
Expand Up @@ -539,12 +539,15 @@ public static function replace(
string|array $pattern,
string|callable $replacement = '',
int $limit = -1,
bool $captureOffset = false,
bool $unmatchedAsNull = false,
): string {
if (is_object($replacement) || is_array($replacement)) {
if (!is_callable($replacement, false, $textual)) {
throw new Nette\InvalidStateException("Callback '$textual' is not callable.");
}
return self::pcre('preg_replace_callback', [$pattern, $replacement, $subject, $limit]);
$flags = ($captureOffset ? PREG_OFFSET_CAPTURE : 0) | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0);
return self::pcre('preg_replace_callback', [$pattern, $replacement, $subject, $limit, 0, $flags]);

} elseif (is_array($pattern) && is_string(key($pattern))) {
$replacement = array_values($pattern);
Expand Down
4 changes: 4 additions & 0 deletions tests/Utils/Strings.replace().phpt
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,7 @@ Assert::same('#@ @@@#d!', Strings::replace('hello world!', [
]));
Assert::same(' !', Strings::replace('hello world!', '#\w#'));
Assert::same(' !', Strings::replace('hello world!', ['#\w#']));

// flags & callback
Assert::same('hell0o worl9d!', Strings::replace('hello world!', '#[e-l]+#', fn($m) => implode($m[0]), captureOffset: true));
Strings::replace('hello world!', '#e(x)*#', fn($m) => Assert::null($m[1]), unmatchedAsNull: true);

0 comments on commit a08d1e4

Please sign in to comment.