The strcspn() function in PHP calculates the length of the initial segment of a string that does not contain any of the specified "disallowed" characters. It remains fundamentally the same in PHP 8.4 and 8.5, with one notable bug fix in 8.4 and a performance improvement.
Syntax and Parameters
The function signature is consistent across these versions:
strcspn(string $string, string $characters, int $offset = 0, ?int $length = null): int
→$string: The string to examine.
→$characters: A string containing every character you want to stop at (the "mask").
→$offset: Optional Where to start searching. Negative values count from the end of the string.
→$length: Optional The maximum number of characters to examine. Negative values mean "stop this many characters from the end".
What is New in PHP 8.4 & 8.5?
PHP 8.4 Bug Fix: Prior to 8.4, if the $characters mask was an empty string (""), the search would incorrectly stop at the first null byte ( ) found in the input string. This has been fixed in PHP 8.4, so an empty mask now correctly examines the entire string.
PHP 8.5 Performance: According to PHP is upgrade notes, the performance of strcspn() (along with strspn()) has been greatly improved. It now runs in linear time (O(n)) instead of being bounded by quadratic time (O(n²)), making it much faster for very long strings.
Practical Examples
Example 1: Basic Usage Find how many characters come before the first vowel.
<?php
$string = "banana";
// a is the disallowed character
$length = strcspn($string, a );
var_dump($length); // Output: int(1) because "b" comes before "a"
?>
Explanation: The initial segment "b" contains no a , so its length is 1.
Example 2: Using Offset and Length Examine a specific slice of the string.
<?php
$string = "abcdhelloabcd";
// Start 9 characters from the end ("helloabcd"), search for a
$length = strcspn($string, a , -9);
var_dump($length); // Output: int(5) for "hello"// Start 9 from the end, and stop 5 from the end
$length2 = strcspn($string, a , -9, -5);
var_dump($length2); // Output: int(4) for "hell"
?>
Explanation: The offset and length allow you to perform the check on a substring without manually calling substr() first.
Example 3: Practical Validation (Forbidden Characters) A common use case is checking if a filename contains illegal characters. If the length returned by strcspn() is less than the total string length, a forbidden character was found.
<?php
$filename = "my:file.txt";
$forbidden = "\?*:/@|<> ; // Characters not allowed in filenamesif (strlen($filename) != strcspn($filename, $forbidden)) {
echo "Error: The filename contains forbidden characters.";
} else {
echo "Filename is clean.";
}
// Output: Error: The filename contains forbidden characters.
?>
Explanation: The colon (:) is in the forbidden list, so strcspn stops counting before the end, causing the lengths to differ.