导航首页 » 技术教程 » PHP字符串函数sscanf()的用法
PHP字符串函数sscanf()的用法 145 2023-12-12   

sscanf

(PHP 4 >= 4.0.1, PHP 5)

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

说明

mixed sscanf ( string $str , string $format [, mixed &$... ] )

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

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

参数

str

将要被解析的 字符串.

format

The interpreted format for 解析str的格式, 除了以下不同外,其余的见 sprintf()的描述文档: 函数不区分语言地区 F, g, G 和 b 不被支持. D 表示十进制数字. i stands for integer with base detection. n stands for number of characters processed so far.

...

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

返回值

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

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

范例

Example #1 sscanf() 例子

<?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) . "-$dayn";
?>

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

Example #2 sscanf() - using optional parameters

<?php
// get author info and generate DocBook entry
$auth = "24tLewis Carroll";
$n = sscanf($auth, "%dt%s %s", $id, $first, $last);
echo "<author id='$id'>
    <firstname>$first</firstname>
    <surname>$last</surname>
</author>n";
?>

参见

fscanf() - 从文件中格式化输入 printf() - 输出格式化字符串 sprintf() - Return a formatted string


!!!站长长期在线接!!!

网站、小程序:定制开发/二次开发/仿制开发等

各种疑难杂症解决/定制接口/定制采集等

站长微信:lxwl520520

站长QQ:1737366103