phpscanfgreedy

Prevent sscanf() from consuming '-' with %s placeholder


It can distinguishes between decimal and '-'

$str = "1995-25";
$pat = sscanf( $str , "%d-%d);
print_r($pat);

It can also distinguish first '-' and following string

$str = "-of";
$pattern = sscanf ( $str , "-%s" );
print_r ( $pattern );

but when it comes to signify '-' in middle of a string it assumes '-' as string and more surprisingly the first %s reads it to the last even considering 4 as string

$str = '-of-america-4';
$pat = sscanf ($str , "-%s-%s-%d");
print_r($pat);
// outputs [0] => of-america-4

Solution

  • %s is a greedy match, you could use %[^-]

    <?php
    $str = '-of-america-4';
    $pat = sscanf($str , '-%[^-]-%[^-]-%d');
    print_r($pat);
    
    Array
    (
        [0] => of
        [1] => america
        [2] => 4
    )