PHP Tutorial - PHP strcspn() Function






Definition

The strcspn() function returns the number of characters including whitespaces found in a string before the index of the specified characters.

Syntax

PHP strcspn() Function has the following syntax.

strcspn(string,char,start,length)

Parameter

ParameterIs RequiredDescription
stringRequired.String to search
charRequired.Characters to search for
startOptional.Where in string to start
lengthOptional.Length of the string to search




Return

PHP strcspn() Function returns the number of characters found in a string before the specified characters

Example 1

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.

Example 2

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.





Example 3

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.