The sscanf Function
The sscanf function analyzes a string using the specified format,
and returns values. The first parameter of the function is the string to be analyzed,
the second is the format string, and the subsequent parameters (optional) are variables
into which the parsing results will be written.
The format string uses special characters (format specifiers), which begin with the % sign and control output formatting.
Syntax
sscanf(string $str, string $format [, mixed &$... ]): mixed
Format Specifiers
| Specifier | Description |
|---|---|
%s |
String |
%d |
Signed integer (decimal) |
%u |
Unsigned integer (decimal) |
%f |
Floating-point number (locale aware) |
%F |
Floating-point number (non-locale aware) |
%c |
Character by ASCII code |
%x |
Integer in hexadecimal number system (lowercase) |
%X |
Integer in hexadecimal number system (uppercase) |
%o |
Integer in octal number system |
%b |
Integer in binary number system |
%e |
Scientific notation (lowercase) |
%E |
Scientific notation (uppercase) |
%g |
Shorter of %e or %f |
%G |
Shorter of %E or %F |
%% |
A percent sign |
Example
Parse a string, extracting a number and text:
<?php
$res = sscanf("42 is the answer", "%d is %s");
print_r($res);
?>
Code execution result:
[42, 'the']
Example
Parse a date into its components:
<?php
$date = "2023-12-31";
list($year, $month, $day) = sscanf($date, "%d-%d-%d");
echo "Year: $year, Month: $month, Day: $day";
?>
Code execution result:
'Year: 2023, Month: 12, Day: 31'