PHP sscanf() Tutorial 🎯

beginner
24 min

PHP sscanf() Tutorial 🎯

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! πŸ“

What is sscanf()? πŸ’‘

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.

Understanding the Basics πŸ“

The basic syntax of sscanf() is as follows:

php
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.

Breaking Down the Format String πŸ“

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 character

Practical Example 🎯

Let's take a look at a practical example:

php
$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 )

Advanced Example 🎯

In our advanced example, we'll create a simple web application to parse user input:

php
<!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.

Quiz πŸ’‘

Quick Quiz
Question 1 of 1

What does the `sscanf()` function do in PHP?