PHP sscanf() function
Example
Parsing string:
<?php $str = "age:30 weight:60kg"; sscanf($str, "age:%d weight:%dkg", $age, $weight); // Display type and value var_dump($age, $weight); ?>
Definition and Usage
The sscanf() function parses input from a string based on the specified format. The sscanf() function parses strings into variables based on the format string.
If only two parameters are passed to this function, the data will be returned in the form of an array. Otherwise, if additional parameters are passed, the parsed data will be stored in these parameters. If the number of delimiters is greater than the number of variables containing them, an error will occur. However, if the number of delimiters is less than the number of variables containing them, the additional variables will contain NULL.
Related functions:
Syntax
sscanf(string,format,arg1,arg2,arg++)
Parameter | Description |
---|---|
string | Required. Specifies the string to be read. |
format |
Required. Specifies the format to be used. Possible format values:
Additional format values. Must be placed between % and the letter (e.g., %.2f):
Note:If multiple of the above format values are used, they must be used in the order specified above. |
arg1 | Optional. The first variable to store the data. |
arg2 | Optional. The second variable to store the data. |
arg++ | Optional. The third, fourth variables, and so on, to store the data. |
Technical Details
Return Value: | If only two parameters are passed to this function, the data will be returned in array form. Otherwise, if additional parameters are passed, the parsed data will be stored in these parameters. If the number of delimiters is greater than the number of variables containing them, an error will occur. However, if the number of delimiters is less than the number of variables containing them, the extra variables will contain NULL. |
PHP Version: | 4.0.1+ |
More Examples
Example 1
Use 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); ?>