PHP sscanf() Function
The PHP sscanf() function parses input from a string according to the specified format. The function reads from string and interprets it according to the specified format.
If only two parameters were passed, the values parsed will be returned as an array. 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 string, null will be returned.
Syntax
sscanf(string, format, vars)
Parameters
string |
Required. Specify the input string being parsed. | ||||||||||||||||||||||||||||||
format |
Additional format value width can be placed between the % and the specifier, (e.g. %10f). This can be used to specify an integer which tells minimum width held of to the variable value. | ||||||||||||||||||||||||||||||
vars |
Optional. Specify variables by reference which will contain the parsed values. |
Return Value
If only two parameters were passed, the values parsed will be returned as an array. 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 string, null will be returned.
Example: sscanf() example
The example below shows the usage of sscanf() function.
<?php //getting name list($name) = sscanf("name:John", "name:%s"); //getting city list($city) = sscanf("city:London", "city:%s"); //and date of birth $DOB = "15 October 1995"; list($day, $month, $year) = sscanf($DOB, "%d %s %d"); echo "$name lives in $city.\n"; echo "His DOB is on $day-".substr($month, 0, 3)."-$year.\n"; ?>
The output of the above code will be:
John lives in London. His DOB is on 15-Oct-1995.
Example: using optional parameters
The example below shows how to use optional parameters with this function.
<?php $info = "name:John city:London 25 July 1986"; //getting name, city and date of birth sscanf($info, "name:%s city:%s %d %s %d", $name, $city, $day, $month, $year); echo "$name lives in $city.\n"; echo "His DOB is on $day-".substr($month, 0, 3)."-$year.\n"; ?>
The output of the above code will be:
John lives in London. His DOB is on 25-Jul-1986.
❮ PHP String Reference