What is strcspn in PHP?

The strcspn function in PHP is used to find the length of a substring before a specific character in the string is found.

Note: The strcspn function is not binary-safe.

Syntax

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

Parameters

strcspn requires two mandatory parameters:

  • string: the string to search in.
  • characters: the string that contains any disallowed character (note: can be more than one).

In addition, the strcspn function also accepts:

  • offset: specifies the position to start searching the string; set to 0 by default.
  • length: specifies the length of the string to search in; set to null by default.

Return value

The strcspn function returns the length of the string until it finds a character in characters.

Code

In the example below, we check three different strings.

<?php
var_dump(strcspn('abcd', 'b'));
var_dump(strcspn('hello educative!', '!', 5));
var_dump(strcspn('hello educative!', '!', 5, 3));

Note: In the third case, there is no ! in the substring, so the output is the length of the substring.

Free Resources