PHP functions strcspn() and strspn()

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

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

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

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:

Did you find this article valuable?

Support Yongyao Yan by becoming a sponsor. Any amount is appreciated!