Skip to content

strspn()

Introduction

The strspn() function in PHP calculates the length of the initial segment of a string that consists entirely of characters contained within a specified mask. In this article, we will discuss the strspn() function in detail and how it can be used in PHP.

Understanding the strspn() function

The syntax for using the strspn() function in PHP is as follows:

The PHP syntax of the strspn()

php
strspn(string $subject, string $mask, int $start = 0, ?int $length = null) : int

Here, $subject is the string that we want to calculate the length of the initial segment of. The $mask parameter is the mask string, which is a string that contains a list of allowable characters. The $start parameter is an optional parameter that specifies the starting position for the search, and the $length parameter is also an optional parameter that specifies the maximum length to search for.

The strspn() function scans the $subject string starting from the $start position, and returns the length of the initial segment of the string that matches the characters in the $mask string. If the $length parameter is specified, the function stops scanning after that length is reached.

Example Usage

Here is an example usage of the strspn() function in PHP:

Example of PHP strspn()

php
<?php

$string = "Hello World";
$mask = "HeloWrd";
$start = 0;
$length = null;

$result = strspn($string, $mask, $start, $length);

echo "The length of the initial segment of '$string' that matches the characters in '$mask' is $result";

In the example above, we define a string $string and a mask string $mask. We use the strspn() function to calculate the length of the initial segment of the $string that matches the characters in the $mask. The function stops scanning at the first character not found in the mask. Since the space at index 5 is not in $mask, the output will be "The length of the initial segment of 'Hello World' that matches the characters in 'HeloWrd' is 5".

Conclusion

The strspn() function in PHP is a useful tool for calculating the length of the initial segment of a string that matches a specified set of characters. Note that the function is case-sensitive. For finding the length of the initial segment that does not match a mask, consider using its counterpart, strcspn(). By understanding how to use these functions, developers can create more efficient and effective PHP applications.

Practice

What is the main function of the strspn() function in PHP?

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.