PHP » Strings » strspn()

Syntax:
int strspn(string s1, string s2)
s1
The string to be counted.
s2
Characters that count.

Checks character occurrences in a string.

This function returns how far into the first string, characters from only the second string appear. The result is returned as a number of characters.

Examples

Code:
<?php

$array1 = range(0, 9);
$array2 = range("a", "z");
$chars = implode("", $array1) . implode("", $array2);
$username = "smith!";

print "Legal characters: $chars<br>";
if (($n = strspn($username, $chars)) != strlen($username)) {
   print "$n legal characters in username \"$username\". It is not a legal username.";
}

?>
Output:
Legal characters: 0123456789abcdefghijklmnopqrstuvwxyz
5 legal characters in username "smith!". It is not a legal username.
Explanation:

One use of this function is to check that the characters of a string belong to a specific set.

See Also: