function replace()

in src/regex/regex.php [99:128]


function replace(
  string $haystack,
  Pattern<Match> $pattern,
  string $replacement,
  int $offset = 0,
)[]: string {
  // replace is the only one of these functions that calls into a native
  // helper other than match. It needs its own helper to be able to handle
  // backreferencing in the `$replacement` string. Our offset handling is
  // trivial so we do it here rather than pushing it down into the helper.
  $offset = _Private\validate_offset($offset, Str\length($haystack));

  if ($offset === 0) {
    list ($result, $error) =
      _Private\_Regex\replace($haystack, $pattern, $replacement);
    if ($error is nonnull) {
      throw new namespace\Exception($pattern, $error);
    }
    return $result as nonnull;
  }

  $haystack1 = Str\slice($haystack, 0, $offset);
  $haystack2 = Str\slice($haystack, $offset);
  list ($result, $error) =
    _Private\_Regex\replace($haystack2, $pattern, $replacement);
  if ($error is nonnull) {
    throw new namespace\Exception($pattern, $error);
  }
  return $haystack1 . ($result as nonnull);
}