The sscanf() function parses a string into variables based on the format string.
PHP sscanf() Function has the following syntax.
sscanf(string,format,arg1,arg2,...argn)
Parameter | Is Required | Description |
---|---|---|
string | Required. | String to read |
format | Required. | Format to use. |
arg1 | Optional. | The first variable to store data in |
arg2 | Optional. | The second variable to store data in |
argn | Optional. | The third, fourth, and so on, to store data in |
Possible format values:
Additional format values. These are placed between the % and the letter (example %.2f):
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.
Parse a string:
<?php
$str = "Proce:30 B:60kg";
sscanf($str,"Price:%d weight:%dkg",$price,$weight);
var_dump($weight);
?>
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);
?>
The code above generates the following result.