Core Function StrSpn
StrSpn( <subject>, <mask>, <start>, <length> )
Contents |
Description
Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask.
Parameters
subject
The string to examine.
mask
The list of allowable characters (as a string).
start
The position in subject to start searching.
If start is given and is non-negative, then strspn() will begin examining subject at the start'th position.
For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth.
If start is given and is negative, then strspn() will begin examining subject at the start'th position from the end of subject.
length
The length of the segment from subject to examine.
If length is given and is non-negative, then subject will be examined for length characters after the starting position.
If lengthis given and is negative, then subject will be examined from the starting position up to length characters from the end of subject.
Return Value
Returns the length of the initial segment of subject which consists entirely of characters in mask.
Remarks
None.
Example
// subject does not start with any characters from mask say(strspn("foo", "o")); // 0 // examine two characters from subject starting at offset 1 say(strspn("foo", "o", 1, 2)); // 2 // examine one character from subject starting at offset 1 say(strspn("foo", "o", 1, 1)); // 1
Check if a phone number is valid
$digits='0123456789'; $phone = "Cat"; if (strlen($phone) != strspn($phone,$digits)) echo "Illegal characters\n"; else echo "Good characters\n"; $phone = "777"; if (strlen($phone) != strspn($phone,$digits)) echo "Illegal characters\n"; else echo "Good characters\n";
Using StrSpn to extract specific text from a string
// Make a string $str = "19421ff49deTesty"; // Extract numbers $npos = StrSPN($str, 0..9); if($npos == 0) die("Could not find the numbers"); $Numbers = substr($str, 0, $npos); // Extract hex digits $hpos = StrSPN($str, (0..9) . ('A'..'F') . ('a'..'f'), $npos); if($hpos == 0) die("Could not find the hex numbers"); $Hex = substr($str, $npos, $hpos); // Extract what is left $Rest = substr($str, $npos + $hpos); // Print the result say "The numbers are '$Numbers'"; say "The hex is '$Hex'"; say "The rest is '$Rest'"; // The numbers are '19421' // The hex is 'ff49de' // The rest is 'Testy'