PHP strcspn() Function
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.|
The basic syntax of the
strcspn() function is given with:
The following example shows the
strcspn() function in action.
<?php // Sample string $str = "Hello World!"; // Defining mask $mask = "W"; // Find length of initial portion of string not matching mask echo strcspn($str, $mask); ?>
strcspn() function accepts the following parameters.
|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.|
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:
<?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.
<?php echo strcspn("Hello World!", "o", 6, 5); ?>