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中文網其他相關文章!