substr_replace() Function Use in PHP 8.4 and PHP 8.5

substr_replace() works identically in PHP 8.4 and PHP 8.5. There are no version-specific changes for this function in either release. The only recent changelog entry is from PHP 8.0.0, where the $length parameter became nullable.

Function

substr_replace() replaces a portion of a string (defined by an offset and an optional length) with a new string. It can also accept arrays to perform replacements on multiple strings simultaneously.

Signature:

substr_replace(
   array|string $string,
   array|string $replace,
   array|int $offset,
   array|int|null $length = null
): string|array

Key Parameters:

$offset: If positive, replacement starts at this position. If negative, it starts this many characters from the end of the string.
$length: The number of characters to replace. If omitted (null), it replaces everything from the offset to the end of the string. If 0, it inserts the replacement without deleting anything. If negative, it stops replacing that many characters from the end.

Example

A common use case is masking a portion of a string, like hiding part of a credit card or phone number.

<?php
$phone = "1234567890";

// Replace 4 characters starting at index 3 (the "4567")
$masked = substr_replace($phone, "****", 3, 4);

echo $masked;
// Outputs: 123****890
?>

Here, offset is 3 (starting after "123"), and length is 4 (covering "4567"), which gets replaced by the asterisks.

18 Views