phpscanfgreedy

When used in sscanf(), %s does not stop matching when it encounters the symbol that follows the %s


I try to parse string with php using sscanf():

$n = sscanf($line, "%s.%s.%s=%s", $ws, $layer, $perm, $role);
echo $ws." - ".$layer." - ".$perm." - ".$role."\n";

And get output:

*.*.r=* -  -  -
topp.*.a=jdbs_watcher -  -  -

Input examples:

 *.*.r=*
 topp.*.a=jdbs_watcher

What i expect to see for second string:

topp - * - a - jdbc_watcher

Why whole string has been put into $ws variable?


Solution

  • use ^ to avoid to be too greedy:

    <?php
    $line = 'topp.*.a=jdbs_watcher';
    $n = sscanf($line, "%[^.].%[^.].%[^=]=%s", $ws, $layer, $perm, $role);
    echo $ws." - ".$layer." - ".$perm." - ".$role."\n";