PHP String sscanf() Function



The PHP String sscanf() function is used to parse input from a string following a preset format. The sscanf() function parses a string into variables based on its format string.

If only two parameters are passed to this function, the results will be given as an array. Otherwise, optional parameters are given and used to store parsed data. An error occurs when there are more specifiers than variables. But if there are fewer specifiers than variables, the additional variables are NULL.

Syntax

Below is the syntax of the PHP String sscanf() function −

array|int sscanf ( string $string, string $format, mixed &...$vars )

Parameters

Here are the parameters of the sscanf() function −

  • $string − (Required) This is used to parse the string.

  • $format − (Required) This option returns the intended string using the format %d for integers and %f for floating point numbers.

  • $vars − (Optional) This parameter defines an additional variable to store extracted values.

Return Value

The sscanf() function returns an array. If optional parameters are passed and used to store parsed data. An error occurs when there are more specifiers than variables. However, if there are fewer specifiers than variables, the additional variables are NULL.

PHP Version

First introduced in core PHP 4.0.1, the sscanf() function continues to function easily in PHP 5, PHP 7, and PHP 8.

Example 1

First we will show you the basic example of the PHP String sscanf() function to parse an integer from a simple string.

<?php
   // Define a string
   $string = "42";

   // Using sscanf() to extract an integer
   $result = sscanf($string, "%d");

   // Display the result
   print_r($result); 
?>

Output

Here is the outcome of the following code −

Array
(
   [0] => 42
)

Example 2

In the below PHP code we will try to use the sscanf() function to extract an integer and a float number from a string.

<?php
   // Define a string with an integer and a float
   $string = "Age: 25, Height: 5.9";

   // Using sscanf() to extract both values
   $result = sscanf($string, "Age: %d, Height: %f");

   // Display the result
   print_r($result); 
?> 

Output

This will generate the below output −

Array
(
   [0] => 25
   [1] => 5.9
)

Example 3

This program uses the sscanf() function to extract date and time components from a complex string.

<?php
   // Define a string
   $string = "Event on 2024-12-11 at 14:30";

   // Using sscanf() to get year, month, day, hour and minute
   sscanf($string, "Event on %d-%d-%d at %d:%d", $year, $month, $day, $hour, $minute);

   // Display the result
   echo "Year: $year\n";   
   echo "Month: $month\n"; 
   echo "Day: $day\n";    
   echo "Hour: $hour\n";  
   echo "Minute: $minute\n"; 
?> 

Output

This will create the below output −

Year: 2024
Month: 12
Day: 11
Hour: 14
Minute: 30
php_function_reference.htm
Advertisements