sscanf()
Our article is about the PHP function sscanf(), which is used to parse input from a string. This function is useful for extracting data from strings that have a
The sscanf() function parses input from a string, making it useful for extracting data from strings with a consistent format. This article covers its syntax, usage, and examples.
The sscanf() function is used to parse input from a string. The syntax of the sscanf() function is as follows:
The PHP syntax of the sscanf()
array|int sscanf ( string $str , string $format , mixed &$... )The function takes two required parameters: $str and $format. The $str parameter is the string to be parsed, and the $format parameter is a string that specifies the format of the input. It uses format specifiers like %s for strings and %d for integers. The function returns an array of extracted values when called with three or more arguments, or an integer count of successfully matched fields otherwise.
Here is an example of how to use the sscanf() function:
Example of PHP sscanf()
<?php
$input = 'John 25';
sscanf($input, '%s %d', &$name, &$age);
echo $name . "\n"; // Output: John
echo $age; // Output: 25
?>In this example, we have a string variable $input that we want to extract data from. We use the sscanf() function to extract the name and age from the string.
The output of this code will be:
John
25As you can see, the sscanf() function has extracted the name and age from the string.
The sscanf() function is a reliable tool for parsing structured strings. By mastering it, you can write more efficient PHP code.
We hope this article has been helpful in understanding the sscanf() function in PHP.
Practice
What is the sscanf() function used for in PHP?