PHP Function Reference

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

Required. Specify the format string. The possible values of %specifier are:

%specifierDescription
%%Returns a percent sign
%cThe character according to the ASCII value
%dSigned decimal number (negative, zero or positive)
%DSigned decimal number (negative, zero or positive)
%iInteger with base detection
%eScientific notation using a lowercase (e.g. 1.2e+3)
%EScientific notation using a uppercase (e.g. 1.2E+3)
%uUnsigned decimal number (zero or positive)
%fFloating-point number
%oOctal number
%sString (stops reading at any whitespace character)
%xHexadecimal number (lowercase letters)
%XHexadecimal number (uppercase letters)
%nNumber of characters processed so far

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