How to Use strcspn() Function in PHP 8.1 and 8.2 with Example?

Support PHP Version: PHP 7.1, PHP 7.2, PHP 7.3, PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2, PHP 8.3 With Latest All Version Support.

Hello Friends Today, through this tutorial, I will tell you How to Use `strcspn()` function using PHP, PHP 8, PHP 8.1, PHP 8.2 With Example. The `strcspn()` function in PHP is used to find the length of the initial segment of a string consisting entirely of characters not in a specified mask. It returns the length of the segment found.

Here’s the syntax of the `strcspn()` function:

<?php
strcspn(string $str1, string $str2 [, int $start [, int $length ]]): int|false
?>

1. `$str1`: The string to search in.
2. `$str2`: The string containing the characters to search for.
3. `$start` (optional): The position in `$str1` to start searching.
4. `$length` (optional): The maximum length of the segment to search for.

Now, let’s see an example of how to use `strcspn()`:

<?php

// Example 1
$str1 = "Hello World";
$str2 = "aeiou";
$length = strcspn($str1, $str2);
echo "The length of the initial segment not containing any vowels is: $length\n"; 
// Output: 2

// Example 2
$str1 = "12345abcde";
$str2 = "abcdefghijklmnopqrstuvwxyz";
$length = strcspn($str1, $str2);
echo "The length of the initial segment not containing any alphabet characters is: $length\n"; 
// Output: 5

?>

In the first example, `strcspn()` is used to find the length of the initial segment of the string `$str1` that does not contain any vowels specified in `$str2`. In the second example, it finds the length of the initial segment of the string `$str1` that does not contain any alphabet characters.

Remember that `strcspn()` returns `false` if an error occurs. So, it’s good practice to handle this possibility in your code.