The `sscanf()` function in PHP parses input from a string according to a specified format, similar to how `scanf()` works in C. It's useful for extracting data from formatted strings.PHP 8. PHP 8.1,PHP 8.2,PHP 8.3 and PHP 8.4.
Basic Syntax
<?php
sscanf(string $str, string $format, mixed &...$vars): mixed
?>
Example Usage in PHP 8.2
<?php
// Example 1: Basic string parsing
$string = "Name: John Doe Age: 30";
$result = sscanf($string, "Name: %s %s Age: %d", $firstName, $lastName, $age);
echo "First Name: $firstName\n";
echo "Last Name: $lastName\n";
echo "Age: $age\n";
echo "Number of matches: $result\n\n";
?>
Common Format Specifiers
`%s` - String
`%d` - Signed decimal number
`%f` - Floating-point number
`%x` - Hexadecimal number
%o` - Octal number
`%c` - Single character
Notes for PHP 8.2
1. The function works the same in PHP 8.2 as in previous versions.
2. Type safety is more strictly enforced in PHP 8.2, so ensure your format specifiers match the expected data types.
3. The function returns either:
This function is particularly useful when you need to parse structured data from strings, such as log files, configuration strings, or user input.