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:
The following example shows the sscanf()
function in action.
Example
Run this code »<?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
|
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.
Example
Run this code »<?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.
Example
Run this code »<?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>";
?>