substr_compare() Function Use in PHP 8.4 and PHP 8.5

The substr_compare() function in PHP 8.4 and PHP 8.5 is fundamentally the same. There are no version-specific behavioral changes for this function in either release. The most recent significant change was in PHP 8.2.0 regarding its return value.

Function

substr_compare() performs a binary-safe comparison of a portion of one string (haystack) starting from a specific offset, against another string (needle), for a defined length .

Signature:

substr_compare(    string $haystack,    string $needle,    int $offset,    ?int $length = null,    bool $case_insensitive = false ): int

Key Parameters:

  • $offset: The starting position for the comparison. If negative, it counts from the end of the string.
  • $length: The number of characters to compare. If omitted (or null), it defaults to comparing the full length of the needle (or the remaining length of haystack, whichever is larger).
  • $case_insensitive: Set to true for a case-insensitive comparison.

Return Value: Returns 0 if the compared portions are equal, a negative number if the haystack portion is less than needle, and a positive number if it is greater.

Example

A common use is to check if a string starts with a specific prefix:

<?php
$url = "https://example.com";

// Compare the first 5 characters of $url with "https"
$result = substr_compare($url, "https", 0, 5);

if ($result === 0) {
   echo "The URL is secure (starts with https).";
} else {
   echo "The URL does not start with https.";
}
// Outputs: The URL is secure (starts with https).
?>

By setting the offset to 0 and the length to 5, you directly compare the beginning of the main string without needing to extract a substring first.

Notes

  • Default $length Caution: If you omit the $lengthparameter, it does not default to the length of the needle. It defaults to the larger of the needle is length or the remaining length of the haystack. This can lead to unexpected results if you are not comparing from the very beginning of the string.
  • PHP 8.2+ Return Values: As of PHP 8.2.0, the function is only guaranteed to return -1, 0, or 1. You should not rely on the magnitude of the returned integer (e.g., expecting it to equal the string length difference).
22 Views