Although you link to the PHP manual, the strspn()
function comes from C libraries, along with strlen()
, strcpy()
, strcmp()
, etc.
strspn()
is a convenient alternative to picking through a string character by character, testing if the characters match one of a set of values. It's useful when writing tokenizers. The alternative to strspn()
would be lots of repetitive and error-prone code like the following:
for (p = stringbuf; *p; p++) {
if (*p == 'a' || *p == 'b' || *p = 'c' ... || *p == 'z') {
/* still parsing current token */
}
}
Can you spot the error? :-)
Of course in a language with builtin support for regular expression matching, strspn()
makes little sense. But when writing a rudimentary parser for a DSL in C, it's pretty nifty.