PHP sscanf() Function
Last Updated :
11 Apr, 2023
The PHP sscanf() is an inbuilt function in PHP where the input string is parsed according to the specified or a particular pattern, along with comparing & matching any whitespace in between the format string & input string, which means, even the tab(\t) will be comparing & matches a single space character in between the format string & input string.
Syntax:
sscanf(string $input, string $format, mixed &...$vars): array|int|null
Parameters: This function accepts three parameters that are described below.
- $input: This is the input parameter that gets the string parsed.
- $format: This parameter gets the expected string by using the format like %d is for integer %f for floating point values.
- &$vars: This parameter specifies one more variable to store extracted values.
Return Values: The sscanf() function returns an array when two parameters are passed. This function returns a parsed value in an array otherwise it will return the number of characters. If the error occurs, it will return “null”.
Example 1: The following code demonstrates the sscanf() function.
PHP
<?php
$str = "10,20" ;
sscanf( $str , "%d,%d" , $num1 , $num2 );
echo "Number 1: " . $num1 . "\n" ;
echo "Number 2: " . $num2 ;
?>
|
Output:
Number 1: 10
Number 2: 20
Example 2: The following code demonstrates the sscanf() function.
PHP
<?php
$input_string = "Amit Kumar" ;
$first_name = "" ;
$last_name = "" ;
if (sscanf( $input_string , "%s %s" , $first_name , $last_name ) === 2)
{
echo "First name: " . $first_name . "\n" ;
echo "Last name: " . $last_name . "\n" ;
}
?>
|
Output:
First name: Amit
Last name: Kumar
Reference: https://www.php.net/manual/en/function.sscanf.php
Share your thoughts in the comments
Please Login to comment...