sscanf 根据指定格式解析输入的字符

发表日期:2021-07-01 10:23:23 | 来源: | | 浏览(1007) 分类:字符串 函数

sscanf

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

sscanf根据指定格式解析输入的字符

说明

sscanf(string $str, string $format, mixed &$... = ?): mixed

这个函数 sscanf() 输入类似 printf()sscanf() 读取字符串str 然后根据指定格式format解析, 格式的描述文档见 sprintf()

指定的格式字符串中的任意空白匹配输入字符串的任意空白.也就是说即使是格式字符串中的一个制表符 \t 也能匹配输入 字符串中的一个单一空格字符

参数

str

将要被解析的 字符串.

format

The interpreted format for 解析str的格式, 除了以下不同外,其余的见 sprintf()的描述文档:

  • 函数不区分语言地区
  • F, g, Gb 不被支持.
  • D 表示十进制数字.
  • i stands for integer with base detection.
  • n 代表目前已经处理的字符数。
  • s 遇到任意空格字符时停止读取。

...

可以选参数将以引用方式传入,它们的值将被设置为解析匹配的值

返回值

如果仅传入了两个参数给这个函数,解析后将返回一个数组,否则,如果可选参数被传入,这个函数将返回被设置了值的个数

如果format存在的子字符串比 str内可用的多, -1 将被返回.

范例

示例 #1 sscanf() 例子

<?php 
// getting the serial numberlist($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";
?>

If optional parameters are passed, the function will return the number of assigned values.

示例 #2 sscanf() - using optional parameters

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

参见

集速网 copyRight © 2015-2022 宁ICP备15000399号-1 宁公网安备 64010402001209号
与其临渊羡鱼,不如退而结网
欢迎转载、分享、引用、推荐、收藏。