String Functions

PHP strcspn() Function

Topic: PHP String ReferencePrev|Next


The strcspn() function returns the number of characters present in a string (including whitespaces) before any part of mask (list of disallowed characters) is found.

The following table summarizes the technical details of this function.

Return Value: Returns the length of the initial portion of string that does not contain any characters specified in the mask.
Version: PHP 4+


The basic syntax of the strcspn() function is given with:

strcspn(string, mask, start, length);

The following example shows the strcspn() function in action.

// Sample string
$str = "Hello World!";

// Defining mask
$mask = "W";

// Find length of initial portion of string not matching mask
echo strcspn($str, $mask);


The strcspn() function accepts the following parameters.

Parameter Description
string Required. Specifies the string to work on.
mask Required. Specifies the string containing every disallowed character.
start Optional. Specifies the position in the string to start searching.
length Optional. Specifies the portion of the string to search.

More Examples

Here're some more examples showing how strcspn() function actually works:

The following example returns the length of the initial portion of string that doesn't contains the characters "l" and "o". Let's try it out and see how it works:

echo strcspn("Hello World!", "lo");

In the following example only the portion "World" of the string will be examined, because the position to start searching is 6 and the length of the string to search is 5.

echo strcspn("Hello World!", "o", 6, 5);
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties