strspn()
The strspn() function in PHP is used to calculate the length of the initial segment of a string that consists entirely of characters contained within a
Introduction
The strspn() function in PHP returns the length of the initial segment of a string that consists entirely of characters found in a given mask (a set of allowed characters). As soon as it meets a character that is not in the mask, it stops counting and returns how many characters it matched before that point.
A common way to think about it: "Starting from the beginning, how many characters belong to this allowed set before I hit one that doesn't?" This makes strspn() handy for lightweight validation and parsing — for example, checking how many leading digits a string has, or whether a value is made up only of permitted characters.
This page covers the function's syntax, each parameter (including the often-misunderstood $start and $length), several runnable examples, common gotchas, and how it relates to its counterpart strcspn().
Syntax
strspn(string $string, string $characters, int $offset = 0, ?int $length = null): int| Parameter | Description |
|---|---|
$string | The subject string to examine. |
$characters | The mask — the set of characters that are allowed in the initial segment. The order of characters does not matter. |
$offset | Optional. The position in $string to start counting from. A negative value counts from the end of the string. Defaults to 0. |
$length | Optional. The maximum number of characters to examine. A negative value stops that many characters from the end. Defaults to the rest of the string. |
Return value: an int — the length of the initial matching segment. If the very first examined character is not in the mask, it returns 0.
Note: in the official manual the parameters are named
$stringand$characters. You may also see them called subject and mask — they mean the same thing.
How it works
The function scans $string left to right (starting at $offset) and keeps a running count while each character is present in $characters. The scan halts at the first character that is not in the mask, and that count is returned. It never looks past the first mismatch, even if later characters would have matched.
strspn() is case-sensitive and byte-based (it works on single bytes, so it is not multibyte/UTF‑8 aware).
Basic example
"Hello" (5 characters) is built entirely from letters in the mask "HeloWrd". The next character is a space, which is not in the mask, so scanning stops and the function returns 5. Note that the mask only needs to contain the allowed letters — the W, r, and d are present even though scanning never reaches them.
Counting leading characters
A frequent use case is measuring how many leading characters of a certain kind a string starts with — for example, leading digits:
<?php
$digits = "1234567890";
echo strspn("42 is the answer", $digits); // 2
echo "\n";
echo strspn("abc123", $digits); // 0 — first char 'a' is not a digitBecause "42 is the answer" begins with two digits followed by a space, the result is 2. In the second string the very first character is a letter, so the function returns 0 immediately.
Using $offset and $length
The optional $offset lets you begin counting partway through the string, and $length caps how many characters are examined.
<?php
// Start at index 1 ("oobar"): 'o','o' match, 'b' stops -> 2
echo strspn("foobar", "of", 1); // 2
echo "\n";
// Only examine the first 1 character: 'f' matches -> 1
echo strspn("foobar", "f", 0, 1); // 1A negative $offset counts from the end of the string, and a negative $length stops that many characters before the end — useful when you want to ignore a trailing portion.
Case sensitivity gotcha
strspn() distinguishes uppercase and lowercase. If you need a case-insensitive check, normalize the string first with strtolower():
<?php
echo strspn("Hello", "helo"); // 0 — 'H' is not in the mask
echo "\n";
echo strspn(strtolower("Hello"), "helo"); // 4 — now 'hell' matchesstrspn() vs strcspn()
The two functions are mirror images of each other:
strspn()counts leading characters that are in the mask.strcspn()counts leading characters that are not in the mask (it stops at the first character that is in the mask).
So strcspn("Hello World", " ") returns 5 — the number of characters before the first space. Reach for strcspn() when you want to find how far it is to the first "forbidden" character (like a delimiter). See strcspn() for details.
Related functions
- strcspn() — the complement; counts leading characters not in the mask.
- strpos() — find the position of the first occurrence of a substring.
- substr() — extract part of a string, often combined with
strspn()to slice off the matched segment. - strlen() — get the total length of a string.
Conclusion
strspn() answers a precise question: how long is the run of allowed characters at the start of this string? It is fast, dependency-free, and well suited to validation and simple parsing tasks. Remember that it is case-sensitive and byte-based, that it stops at the first character outside the mask, and that its counterpart strcspn() does the inverse. With these rules in mind you can use it to write concise, efficient string checks.