The strcspn() function returns the number of characters including whitespaces found in a string before the index of the specified characters.
PHP strcspn() Function has the following syntax.
strcspn(string,char,start,length)
Parameter | Is Required | Description |
---|---|---|
string | Required. | String to search |
char | Required. | Characters to search for |
start | Optional. | Where in string to start |
length | Optional. | Length of the string to search |
PHP strcspn() Function returns the number of characters found in a string before the specified characters
Print the number of characters found in "Hello world!" before the character "w":
<?php
echo strcspn("Hello world from java2s.com!","w");
?>
The code above generates the following result.
Set the start and length to search and print the number of characters found in "Hello world!" before the character "w":
<?php
echo strcspn("Hello world from java2s.com!","w",0,15);
// The start position is 0 and the length of the search string is 15.
?>
The code above generates the following result.
The following code shows how to check if the password contains only numbers.
<?php
$password = "331231212345";
if (strspn($password, "1234567890") == strlen($password))
echo "The password cannot consist solely of numbers!";
?>
The code above generates the following result.