PHP sscanf() Function
Example
Parse a string:
<?php
$str = "age:30 weight:60kg";
sscanf($str,"age:%d weight:%dkg",$age,$weight);
// show types and values
var_dump($age,$weight);
?>
Try it Yourself »
The sscanf() function parses input from a string according to a specified 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.
Related functions:
Syntax
sscanf(string,format,arg1,arg2,arg++)
Parameter Values
Parameter | Description |
---|---|
string | Required. Specifies the string to read |
format | Required. Specifies the format to use. Possible format values:
Additional format values. These are placed between the % and the letter (example %.2f):
Note: If multiple additional format values are used, they must be in the same order as above. |
arg1 | Optional. The first variable to store data in |
arg2 | Optional. The second variable to store data in |
arg++ | Optional. The third, fourth, and so on, to store data in |
Technical Details
Return Value: | 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. |
---|---|
PHP Version: | 4.0.1+ |
More Examples
Example
Using the format values %s, %d and %c:
<?php
$str = "If you divide 4 by 2 you'll get 2";
$format = sscanf($str,"%s %s %s %d %s %d %s %s %c");
print_r($format);
?>
Try it Yourself »
❮ PHP String Reference