首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

sscanf

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

sscanf - 根据格式解析字符串的输入

描述

代码语言:javascript
复制
mixed sscanf ( string $str , string $format [, mixed &$... ] )

函数sscanf()是printf()的输入模拟。 sscanf()从字符串str中读取并根据指定的格式进行解释,这在sprintf()的文档中有描述。

格式字符串中的任何空格都与输入字符串中的任何空格匹配。这意味着即使格式字符串中的tab也可以匹配输入字符串中的单个空格字符。

参数

str

输入的字符串正在被解析。

format

str的解释格式,在sprintf()的文档中有描述,但有以下区别:

  • 功能不是区域意识。
  • FgGb不受支持。
  • D 代表十进制数。
  • i 代表带有基本检测的整数。
  • n 代表到目前为止处理的字符数。
  • s 停止阅读任何空白字符。

...

可以通过引用传递变量,该变量将包含分析的值。

返回值

如果只有两个参数传递给此函数,则解析的值将作为数组返回。否则,如果传递了可选参数,该函数将返回分配值的数量。可选参数必须通过引用传递。

如果格式中有更多的子字符串比str中的可用字符串更多,则返回-1。

例子

示例#1 sscanf()示例

代码语言:javascript
复制
<?php
// getting the serial number
list($serial) = sscanf("SN/2350001", "SN/%d");
// and the date of manufacturing
$mandate = "January 01 2000";
list($month, $day, $year) = sscanf($mandate, "%s %d %d");
echo "Item $serial was manufactured on: $year-" . substr($month, 0, 3) . "-$day\n";
?>

如果传递可选参数,则该函数将返回分配值的数量。

示例#2 sscanf() - 使用可选参数

代码语言:javascript
复制
<?php
// get author info and generate DocBook entry
$auth = "24\tLewis Carroll";
$n = sscanf($auth, "%d\t%s %s", $id, $first, $last);
echo "<author id='$id'>
    <firstname>$first</firstname>
    <surname>$last</surname>
</author>\n";
?>

扩展内容

  • fscanf() - 根据格式解析文件的输入
  • printf() - 输出格式化的字符串
  • sprintf() - 返回格式化的字符串

← sprintf

str_getcsv →

扫码关注腾讯云开发者

领取腾讯云代金券