Welcome to our PHP sscanf() tutorial! Today, we're going to dive into one of PHP's powerful functions for formatting and parsing strings. Let's get started! π
sscanf() is a PHP function that reads formatted data from a string. It's similar to the scanf() function in C, but specifically designed for PHP. The function takes a string and a format string as arguments and returns the number of successfully converted elements.
The basic syntax of sscanf() is as follows:
int sscanf ( string $input, string $format [, mixed ...$variables ] )$input: The string containing the data to parse.$format: The format string specifying the type and position of the data to extract.$variables: (Optional) Variables to store the extracted data.The format string is a combination of characters that specify the format of the data to be extracted. Each character corresponds to a certain data type or format.
Here are some common format characters:
%s: String%d: Signed decimal integer%f: Floating-point number%c: Single characterLet's take a look at a practical example:
$input = "Hello World, 42, 3.14";
$variables = [];
sscanf($input, "Hello %s, %d, %f", $variables);
print_r($variables);In this example, we parse the string "Hello World, 42, 3.14" and store the extracted data in the $variables array. The output will be:
Array
(
[0] => World
[1] => 42
[2] => 3.14
)
In our advanced example, we'll create a simple web application to parse user input:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SSCANF Example</title>
</head>
<body>
<form action="" method="post">
<label for="input">Enter a date (DD/MM/YYYY): </label>
<input type="text" id="input" name="input">
<input type="submit" value="Parse">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$input = $_POST['input'];
$variables = [];
$format = "/(\d{2})/(\d{2})/(\d{4})/";
sscanf($input, $format, $day, $month, $year);
echo "The date is: $day/$month/$year";
}
?>
</body>
</html>In this example, we create a simple HTML form that allows users to input a date in the format DD/MM/YYYY. The PHP script then parses the input using a regular expression as the format string and displays the parsed date.
What does the `sscanf()` function do in PHP?