PHP sscanf() Function
In this chapter you will learn:
- Definition for PHP sscanf() Function
- Syntax for PHP sscanf() Function
- Parameter for PHP sscanf() Function
- Format for PHP sscanf() Function
- Additional format values
- Return for PHP sscanf() Function
- Example - Parse a string
- Example - Using the format values %s, %d and %c
Definition
The sscanf() function parses a string into variables based on the format string.
Syntax
PHP sscanf() Function has the following syntax.
sscanf(string,format,arg1,arg2,...argn)
Parameter
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 |
Format
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.
Return
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:
<?php//from j a v a2 s .com
$str = "Proce:30 B:60kg";
sscanf($str,"Price:%d weight:%dkg",$price,$weight);
var_dump($weight);
?>
Example 2
Using the format values %s, %d and %c:
<?php//from ja v a 2 s . c o m
$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.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP str_getcsv() Function
- Syntax for PHP str_getcsv() Function
- Parameter for PHP str_getcsv() Function
- Return for PHP str_getcsv() Function
- Example - Get string value from a CSV line
Home » PHP Tutorial » PHP String Functions