DEV Community

Cover image for PHP functions strcspn() and strspn()
Yongyao Yan
Yongyao Yan

Posted on • Updated on • Originally published at codebilby.com

PHP functions strcspn() and strspn()

Function strcspn()

The function strcspn() finds the length of initial segment not matching mask.

In the code snippet below, we want to find the prefix length of a UK post code. CF34 9LH is the post code string and the disallowed character list is 0123456789. The function strcspn() is called to find the length of the initial segment that does not contain any numbers. So, CF is the string segment and the length is 2.

$p = strcspn('CF34 9LH', '0123456789');
echo "The length is " . $p;
//The length is 2
Enter fullscreen mode Exit fullscreen mode

You can then easily get the prefix of a post code like this:

$postCode = 'CF34 9LH';
$postPrefix = substr($postCode, 0, strcspn($postCode, '0123456789'));
echo "The prefix is " . $postPrefix;
//The prefix is CF
Enter fullscreen mode Exit fullscreen mode

You can also use the function strcspn() for checking a file name whether it contains any invalid characters.

$str = "filename123$/@456";
$invalidChars = "\\/*@$";
$validLen = strcspn($str, $invalidChars);

if ($validLen != strlen($str)) {
    echo "Invalid character found at position " . $validLen;
    //Invalid character found at position 11
}
Enter fullscreen mode Exit fullscreen mode

In the above code snippet, since the file name string $str contains invalid characters, the length of the initial segment, i.e. filename123, is not the same with the whole file name string. The error message is therefore printed out.

Fuction strspn()

On the contrary, the function strspn() gets the length of the initial segment of a string, which consists entirely of characters contained within a given mask.
...

For the rest of the content, please go to the link below:
https://www.codebilby.com/blog/a40-php-functions-strcspn-and-strspn

Top comments (1)

Collapse
 
chuniversiteit profile image
Chun Fei Lung

It’s always nice to learn something new about PHP after so many years, but I fear that by the time I have a good use case for these functions I’ll probably have forgotten about their existence again. πŸ˜‚