String Functions
Advertisements

PHP sscanf() Function

Topic: PHP String ReferencePrev|Next

Description

The sscanf() function parses input from a string according to a format.

The sscanf() function reads from the string and interprets it according to the specified format, which is described in the previous sprintf() function reference chapter.

The following table summarizes the technical details of this function.

Return Value:

If only two parameters are passed to this function, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference.

Also, If there are more substrings expected in the format than there are available within string, null will be returned.
Version: PHP 4.0.1+

Syntax

The basic syntax of the sscanf() function is given with:

sscanf(string, format, var1, var2, ...);

The following example shows the sscanf() function in action.

<?php
// Sample string
$str = "John Carter (26)";

// Parsing the string
sscanf($str, "%s %s (%d)", $first, $last, $age);
echo "$first $last is a $age year old man.";
?>

Parameters

The sscanf() function accepts the following parameters.

Parameter Description
string Required. Specifies the string to parse.
format

Required. Specifies the interpreted format for string, which is described in the previous sprintf() function reference chapter with the following differences:

  • Function is not locale-aware.
  • F, g, G and b are not supported.
  • D stands for decimal number.
  • i stands for integer with base detection.
  • n stands for number of characters processed so far.
  • s stops reading at any whitespace character.
var1, var2, ... Optional. Specifies the variables that will contain the parsed values.

More Examples

Here're some more examples showing how sscanf() function actually works:

In the following example the values parsed will be returned as an array.

<?php
// Sample string
$date = "January 15 2021";

// Parsing the string 
$result = sscanf($date, "%s %d %d");
print_r($result);
?>

The following example shows how to get the equivalent integer rgb values from the hex color values.

<?php
// Sample hex color code
$hex = "#ff8800";

// Parsing string and get rgb values
list($s, $r, $g, $b) = sscanf($hex, "%1s%2x%2x%2x");
echo "<p style='background: rgb($r, $g, $b, 0.5)'>Alpha transparency<p>";
?>
Advertisements
Bootstrap UI Design Templates