sscanf – PHP String Functions
Syntax :
Description :
The sscanf() function parses input from a string according to a string_format. Output will come according to the string_format.
The sscanf() function parses a string into variables based on the format string.
If only two parameters are passed to this function, the data will be returned as an array. Otherwise, if optional parameters are passed, the data parsed are stored in them. If there are more specifiers than variables to contain them, an error occurs. However, if there are less specifiers than variables, the extra variables contain NULL.
Parameter :
[table caption=”” width=”100%” colwidth=”15%|15%|15%|55%” colalign=”left|lef|lef|left”]
Name, Required /Optional, Value Type, Description
string, Required, String , It is the input string.
string_format, Required, String , Specifies the string formar and how to format the variables in it. The interpreted format for string which is described in the documentation for sprintf() with following differences:
,,,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.
,,,Optionally pass in variables by reference that will contain the parsed values.
arg1, Optional, Mixed , Required. The argument to be inserted at the first %-sign in the format string
arg2, Optional, Mixed , Optional. The argument to be inserted at the second %-sign in the format string
arg3, Optional, Mixed , The argument to be inserted at the third and fourth and so on etc. %-sign in the format string.
[/table]
Output :
If only two parameters were passed to this function, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference.
If there are more substrings expected in the format than there are available within str, -1 will be returned.
Related articles : echo(), print(), printf(), sprintf(), fprintf().
sscanf() – PHP Functions Example 1 :
<?php // getting the serial number list($serial) = sscanf("SN/20190102", "SN/%d"); // and the date of manufacturing $mandate = "Feburary 01 2019"; list($month, $day, $year) = sscanf($mandate, "%s %d %d"); echo "Item $serial was manufactured on: $year-" . substr($month, 0, 3) . "-$day\n"; ?>
Output of above code in the browser is as below:
sscanf() – PHP Functions Example 2 : using optional parameters
<?php // get student info and generate entry $stu = "24\tTest Name"; $details = sscanf($stu, "%d\t%s %s", $id, $first, $last); echo "<student id='$id'> <firstname>$first</firstname> <surname>$last</surname> </author>\n"; ?>
Output of above code in the browser is as below:
<firstname>Test</firstname>
<surname>Name</surname>
</author>