Using sscanf to read fixed-length strings

I am trying to sscanfread a bunch of consecutive lines of a fixed length, but it does not work very well. I can print a string with a fixed length:

sprintf('%.5s', 'aaaaabbbbb');

But if I try to use a %.5sfixed-length string to read (for example, the first 5 bytes of the input string), this will not work. eg.

var_dump(sscanf('aaaaabbbbb', '%.5s'));

If I do this, it var_dumpreturns NULL, and I get the following warning:

Warning: sscanf(): Bad scan conversion character "."

I tried %5sin addition to %.5s, but this also does not work. eg.

var_dump(sscanf('aa aabbbbb', '%5s'));

This returns this:

array(1) {
  [0]=>
  string(2) "aa"
}

I want him to return:

array(1) {
  [0]=>
  string(5) "aa aa"
}

Any ideas?

+4
source share
1 answer

, %s.

http://php.net/manual/en/function.sscanf.php, :

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

, :

var_dump(sscanf('aa aabbbbb', '%5[ -~]'));

PHP 5.2.10.

+1

All Articles