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 26, 2021
1 parent fd0a5c0 commit 8015d13
Show file tree
Hide file tree
Showing 2 changed files with 6 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
2 changes: 2 additions & 0 deletions tests/Utils/Strings.replace().phpt
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,5 @@ Assert::same('#@ @@@#d!', Strings::replace('hello world!', [
]));
Assert::same(' !', Strings::replace('hello world!', '#\w#'));
Assert::same(' !', Strings::replace('hello world!', ['#\w#']));
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 8015d13

Please sign in to comment.