PHP sscanf() function
Example
Parse 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 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 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:
附加的格式值。必需放置在 % 和字母之间(例如 %.2f):
注释:如果使用多个上述的格式值,它们必须按照上面的顺序使用。 |
arg1 | 可选。存储数据的第一个变量。 |
arg2 | 可选。存储数据的第二个变量。 |
arg++ | 可选。存储数据的第三、四个变量,依此类推。 |
技术细节
返回值: | 如果只向该函数传递两个参数,数据将以数组的形式返回。否则,如果传递了额外的参数,那么被解析的数据会存储在这些参数中。如果区分符的数目大于包含它们的变量的数目,则会发生错误。不过,如果区分符的数目小于包含它们的变量的数目,则额外的变量包含 NULL。 |
PHP 版本: | 4.0.1+ |
更多实例
例子 1
使用格式值 %s、%d 和 %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); ?>