What is PHP sscanf() Function?
If you want to parse (analyze and convert) inputs from a string into variables based on a specified format, use sscanf() function.
Syntax:
sscanf(string, format, variable1, variable2,…)
Parameters:
The Function has 2 required parameter2 and any number of optional parameters-
string (Required): It specifies the input string.
format (Required): It specifies the pattern to use for formatting the input string. For formatting, the follows the rules that are described in sprint() function, except the followings-
- Function is not locale-aware.
- F, g, G and b are not supported.
- D stands for decimal number.
- i stands for integer with base detection.
- n stands for number of characters processed so far.
- s stops reading at any whitespace character.
- instead of argnum$ suppresses the assignment of this conversion specification.
variable1, variable2,… (Optional): It specifies one or more variables that holds the parsed values.
Return Values:
The return value depends on whether or not the optional variables are used-
- When no optional variables are used: The function returns an array containing all the parsed values.
- When optional variables are used: The function stores the parsed values in those variables and returns those.
- The function returns NULL if there are more formatting rules in the format parameter than available substrings in the input string.
Practical Usages of sscanf() Function:
Here are some practical usages of sscanf() function-
- Converting color codes from Hexadecimal to its equivalent RGB code using %x or %X format specifier-
<?php $Hex_code = 'FF0000'; list($r, $g, $b) = sscanf($Hex_code, '%2x%2x%2x'); echo "RGB color code of Hexadecimal code \"FF0000\" is: $r, $g, $b"; ?>
Output:
RGB color code of Hexadecimal code "FF0000" is: 255, 0, 0
- Extracting data from log file-
<?php $log = "2025-12-29 17:30:05 INFO: User logged in"; list($year, $month, $day) = sscanf($log, "%d-%d-%d"); echo "User's logged in date was: " . $month . "/" . $day . "/" . $year; ?>
Output:
User's logged in date was: 12/29/2025
- Extracting product no. from product code-
<?php $product_code = "CRN/5117"; sscanf($product_code, "CRN/%d", $serial_no); echo "Serial number of the product code ". $product_code . "is: " . $serial_no; ?>
Output:
Serial number of the product code CRN/5117is: 5117
- Parsing from specific delimiter-
<?php $string = "ID: 1, Name: John"; list($id, $name) = sscanf($string, "ID: %d, Name: %s, Sex: %s"); echo "Person name: ". $name . " and his id is: " . $id; ?>
Output:
Person name: John and his id is: 1
- For parsing a string that has fixed patterns, sscanf() is usually faster than preg_match() function.
PHP Version Support:
PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8
Summary: PHP sscanf() Function
The sscanf() function is a built-in PHP function and part of the PHP’s string functions. Use this function to extract information from structural data.