Latest web development tutorials

PHP sscanf () function

PHP String Reference PHP String Reference

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

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:


grammar

sscanf( string,format,arg1,arg2,arg++ )

参数 描述
string 必需。规定要读取的字符串。
format 必需。规定要使用的格式。

可能的格式值:

  • %% - 返回一个百分号 %
  • %c - ASCII 值对应的字符
  • %d - 包含正负号的十进制数(负数、0、正数)
  • %e - 使用小写的科学计数法(例如 1.2e+2)
  • %u - 不包含正负号的十进制数(大于等于 0)
  • %f - 浮点数
  • %o - 八进制数
  • %s - 字符串
  • %x - 十六进制数(小写字母)
  • %X - 十六进制数(大写字母)

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

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

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

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

Running instance »


PHP String Reference PHP String Reference