PHP Function Reference

PHP strcspn() Function



The PHP strcspn() function returns the length of the initial segment of a string consisting entirely of characters not contained within a specified charlist.

If offset and length are omitted, then all of string will be searched. If they are included, the portion of string specified by the offset and length parameters will be searched.

Note: The strcspn() function is a binary-safe.

Syntax

strcspn(string, charlist, offset, length)

Parameters

string Required. Specify the string to search.
charlist Required. Specify the list of disallowed characters to search for.
offset Optional. Specify offset parameter which indicates the starting position in the string.
  • If it is non-negative, then the search starts at that offset position in the string, counting from zero.
  • If it is negative, then the search starts at the offset position from the end of string.
length Optional. Specify the length of the segment from string to examine. Default is to the end of the string.
  • If length is a non-negative number, then string will be examined for length characters after the starting position.
  • If length is a negative number, then string will be examined from the starting position up to length characters from the end of string.

Return Value

Returns the length of the initial segment of the string consisting entirely of characters not contained within charlist.

Example: strcspn() example

The example below shows the usage of strcspn() function.

<?php
//length of initial segment of string 
//containing characters not from 'ABC'
echo strcspn("HELLO WORLD!", "ABC")."\n";

//length of initial segment of string 
//containing characters not from 'ABCD'
echo strcspn("HELLO WORLD!", "ABCD")."\n";

//length of initial segment of string 
//containing characters not from 'ABCDE'
echo strcspn("HELLO WORLD!", "ABCDE")."\n";

//length of initial segment of string 
//starting at offset 2 and length 7 
//which contains characters not from 'ABCDE'
echo strcspn("HELLO WORLD!", "ABCDE", 2, 7)."\n";

//length of initial segment of string 
//starting at offset 1 and length 7 
//which contains characters not from 'ABCDE'
echo strcspn("HELLO WORLD!", "ABCDE", 1, 7)."\n";
?>

The output of the above code will be:

12
10
1
7
0

❮ PHP String Reference