W3docs

strcspn()

The strcspn() function in PHP is used to calculate the length of the initial segment of a string that does not contain any of the characters specified in a

Introduction

The strcspn() function in PHP returns the length of the initial segment of a string that contains none of the characters listed in a second string. In other words, it counts how many characters at the start of a string you can read before you hit any "stop" character. This page explains the syntax, the optional $start and $length parameters, how the function behaves in edge cases, and how it differs from its companion strspn().

The name reads as "string complement span": it spans the part of the string that does not match the given character set. Common uses include finding how far a token runs before a delimiter, validating that a prefix is free of forbidden characters, and lightweight parsing without a regular expression.

Syntax

strcspn(string $string, string $characters, int $offset = 0, ?int $length = null): int
ParameterDescription
$stringThe string being examined.
$charactersThe set of "stop" characters. The order and repetition of characters here do not matter — only the set membership does.
$offsetWhere to start scanning. A positive value counts from the start; a negative value counts from the end of the string. Defaults to 0.
$lengthHow many characters to scan from $offset. A negative value means up to that many characters from the end of the string. Defaults to scanning to the end.

The function returns an int: the number of leading characters (within the scanned window) that are not present in $characters. If the very first character is in the set, it returns 0.

Note: strcspn() works on bytes, not on multibyte characters. For UTF-8 strings with non-ASCII characters, prefer a regular expression (preg_match) instead.

Basic example

php— editable, runs on the server

Here we scan "Hello World" for the first occurrence of either o or e. Reading from the start, H is safe, but the next character e is in the set, so the safe initial segment is just "H" and the function returns 1.

When no stop character is present

If none of the characters in $characters appear in the scanned portion, the function returns the full length of that portion:

<?php

echo strcspn("abcd", "xyz"); // 4 — none of x, y, z occur, so the whole string qualifies

This is handy for asking "does this prefix avoid a set of characters entirely?" — if the return value equals the string length, the string is clean.

A practical example: reading a token up to a delimiter

A frequent real-world use is measuring how many characters appear before a delimiter. The number strcspn() returns is exactly the length you can hand to substr() to extract the leading token:

<?php

$line  = "price: 100USD";
$digits = "0123456789";

$prefixLength = strcspn($line, $digits); // 7 — "price: " before the first digit
$label = substr($line, 0, $prefixLength);

echo $prefixLength;          // 7
echo "\n";
echo $label;                 // price:

The first digit (1) appears at index 7, so the non-digit prefix "price: " is 7 characters long. We then slice that prefix out with substr().

Using $start and $length

The optional $offset and $length parameters restrict the scan to a window of the string:

<?php

// Start scanning at index 6 ("World"); 'W' is itself a stop character → 0
echo strcspn("Hello World", "World", 6); // 0
echo "\n";

// Scan only the first 5 characters ("Hello") for 'l' or 'd' → stops at the first 'l'
echo strcspn("Hello World", "ld", 0, 5); // 2

In the first call the scan begins at offset 6, where the substring is "World"; its first character W is in the stop set, so the result is 0. In the second call the window is limited to "Hello", and the first l sits at index 2, so the result is 2.

strcspn() vs strspn()

These two functions are mirror images:

  • strspn() counts the leading characters that are in the character set (the span matches).
  • strcspn() counts the leading characters that are not in the set (the complement span).

Use strspn() when you have an allow-list ("how long is the run of valid characters?") and strcspn() when you have a stop-list ("how far until I hit a forbidden character?").

  • strpos() — find the position of a single substring rather than any-of a character set.
  • strstr() — return the part of a string from the first match onward.
  • strlen() — get the total length of a string.
  • strtok() — split a string into tokens by a set of delimiters.

Conclusion

strcspn() is a fast, regex-free way to measure how many characters at the start of a string are free of a given set. Because it returns a length, it pairs naturally with substr() for extracting leading tokens, and it complements strspn() for allow-list-style scanning. Remember that it operates on bytes, so reach for preg_match() when you need multibyte-aware matching.

Practice

Practice
What is the purpose of the strcspn() function in PHP?
What is the purpose of the strcspn() function in PHP?
Was this page helpful?