The strspn() function behaves consistently across PHP 8.4 and PHP 8.5. There are no version-specific behavioral changes or deprecations for this function in either release. The official PHP documentation only records one changelog entry for the 8.x series: in PHP 8.0.0, the $lengthparameter became nullable.
Function
strspn() calculates the length of the initial segment of a string that consists entirely of characters from a given mask.
Signature:
strspn(string $string, string $characters, int $offset = 0, ?int $length = null): int
Key Behavior:
- Stops at the first mismatch: It starts from the beginning (or the $offset) and counts characters as long as they are in the $characters list. It returns the count immediately upon encountering a character not in the mask.
- Returns an Integer: The return value is the length of that matching segment, not the string itself.
Examples
1. Basic Usage (Counting Leading Digits)
<?php
$text = "42 is the answer.";
$count = strspn($text, "1234567890");echo $count;
// Outputs: 2
?>
Explanation: It checks "4" (match) and "2" (match). The next character is a space, which is not in the mask, so it stops and returns 2.
2. Using $offset and $length
<?php
// Start at position 1 (the o ), check up to 2 characters
var_dump(strspn("foo", "o", 1, 2));
// Outputs: int(2)// Start at position 1, but only check 1 character
var_dump(strspn("foo", "o", 1, 1));
// Outputs: int(1)
?>
Note: When $offset is used, the returned count starts from that position, not from the beginning of the string.
Note
This function is case sensitive. If you pass "abc" as the string and "A"as the mask, the result will be 0 because lowercase "a" is not in the uppercase mask.