In PHP 8.4 and PHP 8.5, the sscanf() function works the same as in previous versions. It parses input from a string according to a specified format, acting as the input analog of printf() .
Functionality
The function reads a string and interprets it based on a format string. Key behaviors include:
Whitespace matching: Any whitespace in the format (including ) matches any whitespace in the input string .
Return values: With only two parameters, it returns an array of parsed values. With optional reference parameters, it returns the count of assigned values .
Edge cases: Returns null if the format expects more substrings than available; returns -1 if the end of input is reached before any value is parsed (when using optional parameters) .
Example
Example 1: Parsing a serial number and date
<?php
// Extract serial number
list($serial) = sscanf("SN/2350001", "SN/%d");// Extract date components
$mandate = "January 01 2000";
list($month, $day, $year) = sscanf($mandate, "%s %d %d");echo "Item $serial was manufactured on: $year-" . substr($month, 0, 3) . "-$day ";
// Output: Item 2350001 was manufactured on: 2000-Jan-01
?>
This is the standard example from the PHP manual .
Example 2: Using optional reference parameters
<?php
$auth = "24 Lewis Carroll";
$n = sscanf($auth, "%d %s %s", $id, $first, $last);echo "<author id= $id >
<firstname>$first</firstname>
<surname>$last</surname>
</author> ";
// $n equals 3 (number of assigned values)
?>
Here, $id, $first, and $last are populated by reference .