PHP strcspn() Function
Topic: PHP String ReferencePrev|Next
Description
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+ |
Syntax
The basic syntax of the strcspn() function is given with:
The following example shows the strcspn() function in action.
Example
Run this code »<?php
// Sample string
$str = "Hello World!";
// Defining mask
$mask = "W";
// Find length of initial portion of string not matching mask
echo strcspn($str, $mask);
?>
Parameters
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:
Example
Run this code »<?php
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.
Example
Run this code »<?php
echo strcspn("Hello World!", "o", 6, 5);
?>

