How can I get all the digits at the beginning of a string?
Here is an example string: 1&days=800&trans=9aq8ojjfka24qnl10ohktibfs1
In the example above, I would need to extract 1
.
If you need the leading digits - including mulitple zeros - you can scan the string for it. If none exists, the value will be NULL
:
$subject = '1&days=800&trans=9aq8ojjfka24qnl10ohktibfs1';
sscanf($subject, '%[0-9]', $leadingDigits);
echo 'Leading digits are: ', var_dump($leadingDigits);
Outpupt (Demo):
Leading digits are: string(1) "1"
If you do not need leading zeroes, do what vascowhite suggested, that is pretty straight forward. Otherwise:
sscanf($subject, '%d', $leadingDigits);
Returns an integer, too.