(PHP 4 >= 4.0.1, PHP 5, PHP 7)

sscanfInterpreta un string de entrada de acuerdo con un formato


mixed sscanf ( string $str , string $format [, mixed &$... ] )

La función sscanf() es la entrada análoga de printf(). sscanf() lee del string str y lo interpreta de acuerdo con el format especificado, el cual está descrito en la documentación para sprintf().

Cualquier espacio en blanco en el string de formato coincide con cualquier espacio en blanco en string de entrada. Esto significa que incluso un tabulador \t en el string de formato puede coincidir con un caracter simple de espacio en el string de entrada.



El string de entrada para ser interpretado.


El formato interpretado str, el cual está descrito en la documentación para sprintf() con las siguientes diferencia:

  • La función no es consciente de la configuración regional.
  • F, g, G y b no están soportados.
  • D representa número decimal.
  • i representa integer con detección de base.
  • n representa el número de caracteres procesados hasta el momento.


Opcionalmente variables pasadas por referencia que contendrán los valores interpretados.

Valores devueltos

Si sólo se pasan dos parámetros a esta función, los valores interpretados se devolverán como una matriz. De lo contrario, si se pasan parámetros opcionales, la función devolverá el número de valores asignados. Los parámetros opcionales se deben pasar por referencia.

Si hay más substrings esperados en el format que los que hay disponibles en str, será devuelto -1.


Ejemplo #1 Ejemplo de sscanf()

// obtener el número serial
list($serial) = sscanf("SN/2350001""SN/%d");
// y la fecha de manufactura
$mandate "January 01 2000";
$month$day$year) = sscanf($mandate"%s %d %d");
"Item $serial was manufactured on: $year-" substr($month03) . "-$day\n";

Si se pasan parámetros opcionales, la función devolverá el número de valores asignados.

Ejemplo #2 sscanf() - using optional parameters

// obtener la información del autor y generar entrada DocBook
$auth "24\tLewis Carroll";
$n sscanf($auth"%d\t%s %s"$id$first$last);
"<author id='$id'>

Ver también

  • fscanf() - Analiza la entrada desde un archivo de acuerdo a un formato
  • printf() - Imprimir una cadena con formato
  • sprintf() - Devuelve un string formateado

add a note add a note

User Contributed Notes 17 notes

jon at fuck dot org
15 years ago
this function is a great way to get integer rgb values from the html equivalent hex.

list($r, $g, $b) = sscanf('00ccff', '%2x%2x%2x');
9 years ago
FYI - if you are trying to scan from a string which contains a filename with extension. For instance:


= sscanf('file_name.gif', 'file_%s.%s', $fpart1, $fpart2);


The scanned string in the $fpart1 parameter turns out to be 'name.gif' and $fpart2 will be NULL.

To get around this you can simply replace the "." with a space or another "white-space like" string sequence.

I didn't see any other comments on regarding string literals which contain a '.' so I thought I'd mention it. The subtle characteristics of having "white-space delimited" content I think can be a source of usage contention. Obviously, another way to go is regular expressions in this instance, but for newer users this may be helpful.

Just in case someone else spent 10 minutes of frustration like I did. This was seen on PHP Version 5.2.3-1ubuntu6.3.

Searching the bug reports shows another users misunderstanding:
12 years ago
The %[^[]]-trick may seem to work, but it doesn't!

What happens is that sscanf will simply match any characters but an opening square bracket (which is rather rare and that's why it might just seem to work).
But even worse it will expect a ]-character next and continue to match anything.

Now what you can do is make sscanf look for any character but a character that is really never used... a good choice is the linebreak "%[^\\n]", especially in combination with fscanf.

What you can also do is copy and paste any unused ascii character like #001 or something.
elgabos at umail dot ucsb dot edu
15 years ago
After playing around with this for a while, I found that if you use %[^[]] instead of %s (since php has problems with spaces when using %s) it works nicely.

For those that aren't familiar with regular expressions, %[^[]] basically matches anything that isn't nothing.

Hope this helps. - Gabe
11 years ago
To parse a line from an Apache access log in common format:

= array();
$n = sscanf(trim($line), '%s %s %s [%[^]]] "%s %s %[^"]" %d %s "%[^"]" "%[^"]"',
Vincent Jansen
12 years ago
If you just wants filter out information between two parts of a string, i used the following, it works better for me then the sscanf function.

function scanstr($zoekstr,$part1,$part2) {
$firstpos=strpos ($zoekstr, $part1)+strlen($part1);
$lastpos=strpos ($zoekstr, $part2);
$scanresult=substr ($zoekstr, $firstpos, $lastpos-$firstpos);
scanstr ("var1=hello&var2=test&var3=more","var2=","&var3");
5 years ago
One thing to note: unlike C/C++, a variable %n is assigned to will be counted in the return value.
9 years ago


= sscanf('file_name.gif', 'file_%[^.].%s', $fpart1, $fpart2);

'<hr />';




The "^." part avoid the first searched string to be too greedy. But doesn't protect you against an "" input, with bad results!
11 years ago
I've seen several examples of people using brackets to define what look like regexp character classes. In my limited testing I don't think they are genuine character classes but they seem to be similar.

My task was to use sscanf() to parse an array of strings with the format:

number SPACE string_which_may_also_have_spaces

The normal %s conversion command treats spaces as some kind of delimiter. So, you can get the strings if you know beforehand how many "words" there will be. But, my input was variable.

Here's what I came up with: (note use of the dollar-sign 'end of string' hidden delimiter)

sscanf($string_to_parse,'%d %[^$]s',$num,$text);

This conversion command says "look for an integer, then a space, then any string up to the end of the string"
12 years ago
added country code (1) to phone number function:

function formatPhone($phone) {
       if (empty($phone)) return "";
       if (strlen($phone) == 7)
               sscanf($phone, "%3s%4s", $prefix, $exchange);
       else if (strlen($phone) == 10)
               sscanf($phone, "%3s%3s%4s", $area, $prefix, $exchange);
       else if (strlen($phone) > 10)
               if(substr($phone,0,1)=='1') {
                                 sscanf($phone, "%1s%3s%3s%4s", $country, $area, $prefix, $exchange);
                                 sscanf($phone, "%3s%3s%4s%s", $area, $prefix, $exchange, $extension);
               return "unknown phone format: $phone";
       $out = "";
       $out .= isset($country) ? $country.' ' : '';
       $out .= isset($area) ? '(' . $area . ') ' : '';
       $out .= $prefix . '-' . $exchange;
       $out .= isset($extension) ? ' x' . $extension : '';
       return $out;
codeslinger at compsalot dot com
12 years ago
Security Note:

Although it is a very powerful technique, keep in mind that it is easily deceived.

Many successful exploits have been based on scanf attacks.  It should not be used on untrusted input without a lot of additional validation.
narainsbrain at yahoo dot com
16 years ago
apparently, sscanf always splits at spaces, even if spaces are not specified in the format. consider this script:

= "This is a\tsentence with\ttabs";
$scanned = sscanf($str, "%s\t%s\t%s");
join(" : ", $scanned);

this echoes "This : is : a", not the expected "This is a : sentence with : tabs."
this behaviour is fine if your strings don't contain spaces, but if they do you'd be better off using explode().
clcollie at mindspring dot com
17 years ago
Actually sscanf()_always_ returns an array if you specify less return variables than format specifiers. i may change this to return a scalar if only a single format specifier exists.
  Note that sscanf() is (almost) the complete functional equivalent of its "C" counterpart, so you can do the following to get the expected effect :


The array return was a nicety for PHP.
14 years ago
More fun with phones!  This assumes that the phone number is 10 digits, with only numeric data, but it would be easy to check the length of the string first.

function formatPhone($phone) {
        if (empty($phone)) return "";
        sscanf($phone, "%3d%3d%4d", $area, $prefix, $exchange);
        $out = @$area ? "($area) " : "";
        $out .= $prefix . '-' . $exchange;
        return $out;
nmmm at nmmm dot nu
5 years ago
This is more like C/C++ example, but works on PHP too.

= "index.php?id=34&name=john";

print_r(   sscanf($qs, "%[^?]?%[^?]")   );

$qs = "id=34&name=john";

print_r(   sscanf($qs, "id=%[^&]&name=%[^&]")   );
marcus at synchromedia dot co dot uk
14 years ago
In PHP >= 4.3.0, if you use additional reference parameters, you will get this warning:

PHP Warning:  Call-time pass-by-reference has been deprecated - argument passed by value

This clearly has the potential to cause unexpected consequences (vars left empty), and will break existing code. So don't do it! These docs need updating to say this too.

The syntax:

    list($a, $b) = sscanf("hello world", "%s %s");

will work as expected, and doesn't seem to cause any problems with Apache that I've noticed.
Igor Feghali
9 years ago
parses an input string with fixed field sizes that contains data with spaces:

= sscanf("  Vendor: My Vendo Model: Super Model Foo  Rev: 1234"
'  Vendor: %8[ -~] Model: %16[ -~] Rev: %4c',
$vendor, $model, $rev);

$vendor => My Vendo
$model => Super Model Foo
$rev => 1234
To Top