Example 1 — Count Leading Digits
Find how many digits appear before the first non-digit.
<?php
$count = strspn("42 apples", "0123456789");
echo $count, PHP_EOL; How It Works
- Pass the string and a list of digit characters.
- PHP checks "4" and "2", both allowed.
- The third character is a space, which is not allowed.
- It stops there and returns 2.

