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:

  • printf() - Output a formatted string
  • sprintf() - Write a formatted string to a variable

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:

  • %% - Returns a percentage sign %
  • %c - Character corresponding to ASCII value
  • %d - Decimal number with sign (negative, 0, positive)
  • %e - Scientific notation in lowercase (e.g., 1.2e+2)
  • 蒝ecimal number without sign (greater than or equal to 0)
  • %f - Floating-point number
  • %o - Octal number
  • %s - String
  • 0x - Hexadecimal number (lowercase letters)
  • %X - 十六进制数(大写字母)

附加的格式值。必需放置在 % 和字母之间(例如 %.2f):

  • + (在数字前面加上 + 或 - 来定义数字的正负性。默认地,只有负数做标记,正数不做标记)
  • ' (规定使用什么作为填充,默认是空格。它必须与宽度指定器一起使用。)
  • - (左调整变量值)
  • .[0-9] (规定变量值的最小宽度)
  • .[0-9] (规定小数位数或最大字符串长度)

注释:如果使用多个上述的格式值,它们必须按照上面的顺序使用。

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);
?>

运行实例