Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
communitycreator

What is strcspn in PHP?

Dario Vincenzo Tarantini

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

php
communitycreator

CONTRIBUTOR

Dario Vincenzo Tarantini

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring