In this article we’ll see how to use sscanf() to read or parse a string in a customized way. You may have heard of the scan series of functions before, especially in other types of programming. In c based console applications that could read user input and then print text results, scan was the opposite of print. That only has a little bit to do with the function we will be talking about here.

sscanf() isn’t something you will use every day. You could try to pick apart strings with other standard string functions, or use variations on preg_match() or preg_replace(). Regardless there are situations where any of these methods might be best. The first example of sscanf will be pretty simple;

$scanned_float = 0.0;
sscanf("9.64", "%f", $scanned_float);
echo $scanned_float;

You may have guessed that $scanned_float now equals 9.64. The first parameter is the string to be read. The second is a format string based on the format used by the printf() function. Any additional arguments will be filled with values computed from the function, in order. In this case the format means 1 float value. There is one variable to receive it, $scanned_float.

$scanned_float = 0.0;
sscanf("height: 9.64", "%f", $scanned_float);
echo $scanned_float;

But in this case the “scan” fails. Adding height meant the format string did not find the float first, and it basically gave up. $scanned_float actually still equals it’s original number, 0.0, since no number was put into it.

$scanned_float = 0.0;
sscanf("height: 9.64", "height: %f", $scanned_float);
echo $scanned_float;

Making it work with “height: 9.64” was as simple as changing the format string to “height: %f”. $scanned_float is now 9.64.

%s = string

%d = signed integer

%f = float

Those are some of the possible codes (type specifiers) that can be used in the format string, and those are usually the only 3 you will use.

$string1 = '';
$scanned_float = 0.0;
$string2 = '';
$scanned_integer = 0;
sscanf("height: 9.64 width: 120", "%s%f %s%d", $string1, $scanned_float, $string2, $scanned_integer);
echo $string1 . ($scanned_float * 2) . ' / ' . $string2 . $scanned_integer;
//shows: height:19.28 / width:120

In the above example, we start with a string that includes height and width. We want to change the string so height is higher, and there is a / between the values. We basically disassemble the string and put it back together, while doing a math operation on $scanned_float. Notice that 1 space is present in the format string. Spaces in the format string match any whitespace, be it several spaces, a tab, a newline and a space… anyway you’ll get the hang of it with a little practice.

$vars = sscanf("9.64", "height: %f");

You may also use sscanf() with 2 arguments, and the return value will be a numeric array of values in order. Both methods are fine, of course I chose named arguments for my examples.