Parse a string:
<?php$str = "age:30 weight:60kg";sscanf($str,"age:%d weight:%dkg",$age,$weight);// show types and valuesvar_dump($age,$weight );?>The sscanf() function parses input from a string according to a specified format. The sscanf() function parses a string into a variable based on a format string.
If you pass only two arguments to the function, the data will be returned as an array. Otherwise, if additional parameters are passed, the parsed data will be stored in these parameters. If the number of separators is greater than the number of variables containing them, an error occurs. However, if the number of separators is less than the number of variables containing them, the extra variables contain NULL.
Related functions:
printf() - outputs a formatted string
sprintf() - writes a formatted string to a variable
sscanf( string,format,arg1,arg2,arg++ )
parameter | describe |
---|---|
string | Required. Specifies the string to be read. |
format | Required. Specifies the format to be used. Possible format values: %% - returns a percent sign % %c - the character corresponding to the ASCII value %d - decimal number with sign (negative, 0, positive) %e - Use lowercase scientific notation (e.g. 1.2e+2) %u - Decimal number without sign (greater than or equal to 0) %f - floating point number %o - octal number %s - string %x - hexadecimal number (lowercase letters) %X - hexadecimal number (uppercase letters) Additional format values. Must be placed between % and a letter (e.g. %.2f): + (Add + or - in front of a number to define the sign of the number. By default, only negative numbers are marked, and positive numbers are not marked) ' (Specifies what to use as padding, defaults to spaces. It must be used with a width specifier. For example: %'x20s (use "x" as padding)) - (left adjustment variable value) [0-9] (specifies the minimum width of the variable value) .[0-9] (specifies the number of decimal places or the maximum string length) Note: If multiple above format values are used, they must be used in the order above and cannot be disrupted. |
arg1 | Optional. The first variable to store data. |
arg2 | Optional. A second variable to store the data. |
arg++ | Optional. The third and fourth variables that store data. And so on. |
Return value: | If you pass only two arguments to the function, the data will be returned as an array. Otherwise, if additional parameters are passed, the parsed data will be stored in these parameters. If the number of separators is greater than the number of variables containing them, an error occurs. However, if the number of separators is less than the number of variables containing them, the extra variables contain NULL. |
---|---|
PHP version: | 4.0.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);?>