sscanf() 是 PHP 中的预定义函数,它在按照所需格式解析输入字符串后返回已解析的输入字符串。它接受 2 个参数的输入并为我们提供所需的数组,在其他情况下,当传递其他参数(例如可选参数)时,解析的数据将存储在其中。当说明符数量多于包含这些变量的变量时,它会抛出错误,并且如果存在比变量低的说明符,则额外的变量将获取 NULL。
开始您的免费软件开发课程
网络开发、编程语言、软件测试及其他
下面是 PHP sscanf() 的语法:
sscanf(input_string, format, arg1, arg2, arg3....)
输入参数:
1。 input_string: 这是要读取的输入字符串。
2。格式: 我们可以根据需要指定如下列表的格式:
还有一些附加的格式值放置在 % 符号和我们给出的字母之间。 (例如%0.3f)
返回值:这里可能发生两种情况:
下面给出的是提到的示例:
代码:
<?php $text = "Random sentence goes here with numbers 5 and 8"; $f = sscanf($text,"%s %s %s %s %s %s %d %s %d"); print_r($f); ?>
输出:
在此示例中,我们根据需要指定文本。然后使用 sscanf 函数并指定代表我们输入字符串的正确格式。因此,在输出中,确切的字符串显示为数组。仅当格式与数据匹配时才会如此。
代码:
<?php // fetching the unique ID of product list($ID) = sscanf("SN/680001", "SN/%d"); // fetching date of manufacturing $manf = "March 03 2001"; // fetching the date of expiry $expiry = "March 03 2002"; // Parsing using sscanf function list($mon, $day, $yr) = sscanf($manf, "%s %d %d"); list($mon, $day, $yr) = sscanf($expiry, "%s %d %d"); echo "Product $ID was manufactured on $manf and will expire on: $yr-" . substr($mon, 0, 3) . "-$day\n"; ?>
输出:
在此示例中,我们将展示如何检查和显示产品信息,例如其唯一制造 ID 和到期日期。因此,在第一个参数中,我们获取 ID 信息并以 %d 格式解析它。接下来,我们将获取产品的生产日期和有效期,并使用 sscanf 函数解析所需的格式。然后将所有解析出来的东西用一句话展示出来。这里可以添加多个东西来显示我们想要的信息。
Code:
<?php // Fetching designer info and to generate DressInfo entry $design = "13\tCoco Chanel"; $str = sscanf($design, "%d\t%s %s", $ID, $firstname, $lastname); // Displaying all the above details after formatting echo "<author id='$ID'> <firstname>$firstname</firstname> <surname>$lastname</surname> </author>\n"; ?>
Output:
In this example we are using sscanf function to first parse the ID and name of the designer. Then displaying the same in HTML format by splitting the names into first name and last name.
Code:
<?php // We are initializing the string here $arr = "Character PHP and number 7"; // Parsing the input string according to different format $format = sscanf($arr,"%s %c%c%c %s %s %d"); print_r($format); ?>
Output:
In the above example we are first initializing the string as required and this time including a few character sets in combination with strings. The same we are parsing using the sscanf function.
As seen above in all the examples, sscanf function in PHP is basically used to parse any type of the input string as per the requirements. There are a few cases where this function shows inefficiency to parse the strings, where there may be incorrect output when we try to parse a tab delimited string also having normal spaces in between. It also does not give the expected output if in the code there is a file name with its extension where it finds difficult to separate the two in presence of a “.”.
以上是PHP sscanf()的详细内容。更多信息请关注PHP中文网其他相关文章!