PHP sscanf () function
Examples
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);
?>
$str = "age:30 weight:60kg";
sscanf($str,"age:%d weight:%dkg",$age,$weight);
// show types and values
var_dump($age,$weight);
?>
Running instance »
sscanf () function parses input from a string according to the specified format. sscanf () function to parse the string-based format string variable.
If only two parameters passed to the function, the data will be returned in the form of an array. Otherwise, if you pass additional parameter, these parameters are parsed data is stored. If the number is greater than the specifier containing them variable, an error occurs. However, if the number is less than the number of specifiers contain their variables, the extra variables contain NULL.
Related functions:
- the printf () - Output a formatted string
- sprintf () - Writes a formatted string to a variable
grammar
sscanf( string,format,arg1,arg2,arg++ )
参数 | 描述 |
---|---|
string | 必需。规定要读取的字符串。 |
format | 必需。规定要使用的格式。 可能的格式值:
附加的格式值。必需放置在 % 和字母之间(例如 %.2f):
注释:如果使用多个上述的格式值,它们必须按照上面的顺序进行使用,不能打乱。 |
arg1 | 可选。存储数据的第一个变量。 |
arg2 | 可选。存储数据的第二个变量。 |
arg++ | 可选。存储数据的第三、四个变量。依此类推。 |
technical details
return value: | If only two parameters passed to the function, the data will be returned in the form of an array. Otherwise, if you pass additional parameter, these parameters are parsed data is stored. If the number is greater than the specifier containing them variable, an error occurs. However, if the number is less than the number of specifiers contain their variables, the extra variables contain NULL. |
---|---|
PHP version: | 4.0.1+ |
More examples
Example 1
Use the format value% 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);
?>
$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);
?>
Running instance »
PHP String Reference