strspn()

strspn() — Finds the length of the initial segment of a string consisting entirely of characters contained within a given 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.

Signature

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

Parameters

ParameterTypeWhat it takes
$stringstringThe string to examine.
$charactersstringThe list of allowable characters.
$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 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:

// subject does not start with any characters from mask var_dump(strspn("foo", "o")); // examine two characters from subject starting at offset 1 var_dump(strspn("foo", "o", 1, 2)); // examine one character from subject starting at offset 1 var_dump(strspn("foo", "o", 1, 1));

Output:

int(0) int(2) int(1)

Changelog

VersionChange
8.0.0length is nullable now.

See also

strcspn()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page strspn() (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.