strcspn

Going on 10 years of PHP programming and I’m still finding functions that I never knew about. Today it was strcspn which is one of those functions that essentially maps directly to a C counterpart.

int strcspn ( string $subject , string $mask [, int $start [, int $length ]] )

The formal description is:

Find length of initial segment not matching mask

Which translates to, “If $subject contains any characters from $mask, return the number of characters before the first instance of the character found from $mask. If $subject doesn’t contain any characters from $mask, return the string’s length.”
So you could make a mask:

$mask = '2357';

And take some user input:

$input = 'password13';

And a stupid business rule:

Your password must not contain any single digit that is a prime number

$is_valid = strlen( $input ) === strcspn( $input, $mask );

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.