strcspn()

strcspn() — Find length of initial segment not matching mask.

Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

Returns the length of the initial segment of string which does not contain any of the characters in characters.

Signature

strcspn(string $string, string $characters, int $offset = 0, ?int $length = null): int

Parameters

ParameterTypeWhat it takes
$stringstringThe string to examine.
$charactersstringThe string containing every disallowed character.
$offsetintThe position in string to start searching.
$length?intThe length of the segment from string to examine.

Return value

Returns the length of the initial segment of string which consists entirely of characters not in characters. Note: When a offset parameter is set, the returned length is counted starting from this position, not from the beginning of string. When a offset parameter is set, the returned length is counted starting from this position, not from the beginning of string.

Example

A runnable snippet:

$a = strcspn('banana', 'a'); $b = strcspn('banana', 'abcd'); $c = strcspn('banana', 'z'); $d = strcspn('abcdhelloabcd', 'a', -9); $e = strcspn('abcdhelloabcd', 'a', -9, -5); var_dump($a); var_dump($b); var_dump($c); var_dump($d); var_dump($e);

Output:

int(1) int(0) int(6) int(5) int(4)

Changelog

VersionChange
8.4.0Prior to PHP 8.4.0, when characters was the empty string, the search would incorrectly stop at the first null byte in string.
8.0.0length is nullable now.

See also

strspn()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page strcspn() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.