PHP Tutorial - PHP sscanf() Function


The sscanf() function parses a string into variables based on the format string.


PHP sscanf() Function has the following syntax.



ParameterIs RequiredDescription
stringRequired.String to read
formatRequired.Format to use.
arg1Optional.The first variable to store data in
arg2Optional.The second variable to store data in
argnOptional.The third, fourth, and so on, to store data in


Possible format values:

  • %% - Returns a percent sign
  • %c - The character according to the ASCII value
  • %d - Signed decimal number (negative, zero or positive)
  • %e - Scientific notation using a lowercase (e.g. 1.2e+2)
  • %u - Unsigned decimal number (equal to or greather than zero)
  • %f - Floating-point number
  • %o - Octal number
  • %s - String
  • %x - Hexadecimal number (lowercase letters)
  • %X - Hexadecimal number (uppercase letters)

Additional format values

Additional format values. These are placed between the % and the letter (example %.2f):

  • + Forces both + and - in front of numbers. By default, only negative numbers are marked
  • ' Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding)
  • - Left-justifies the variable value
  • [0-9] Set the minimum width held of to the variable value
  • .[0-9] Set the number of decimal digits or maximum string length

Multiple additional format values must be in the same order as above.


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.

Example 1

Parse a string:

$str = "Proce:30 B:60kg";
sscanf($str,"Price:%d weight:%dkg",$price,$weight);


Example 2

Using the format values %s, %d and %c:

$str = "If you divide 4 by 2 you'll get 2";
$format = sscanf($str,"%s %s %s %d %s %d %s %s %c");

The code above generates the following result.