The substr() function behaves identically in PHP 8.4 and PHP 8.5. There are no version-specific changes or deprecations for this function in either release. The most recent behavioral changes date back to PHP 8.0.0.
Function
substr() returns a portion of a string specified by the offset and length parameters.
Signature:
substr(string $string, int $offset, ?int $length = null): string
Key Behavior:
- $offset: If non-negative, the substring starts at that position (0 indexed). If negative, it starts that many characters from the end of the string.
- $length: If positive, it limits the number of characters returned. If negative, that many characters are omitted from the end. If omitted or null, it returns everything from the offset to the end.
- Return Value: Returns the extracted string. As of PHP 8.0.0, it returns an empty string instead of false when the offset is beyond the string length.
Example
A common use case is extracting a portion of a string, such as a file extension or a specific word:
<?php
$string = abcdef ;// Get everything from position 1 onwards
echo substr($string, 1); // Outputs: bcdef// Get 3 characters starting from position 1
echo substr($string, 1, 3); // Outputs: bcd// Get the last character using a negative offset
echo substr($string, -1); // Outputs: f
?>
These examples are standard and work across all supported PHP 8.x versions.