phpscanf

In sscanf(), %s does not stop matching at dot


This doesn't work:

list($value) = sscanf('foo.bar','%s.bar');
echo $value; //foo.bar

While this does:

list($value) = sscanf('foo bar','%s bar');
echo $value; //foo

Any suggestions are really appreciated. Thanks.


Solution

  • %s will greedily capture characters until a whitespace or the end of the string. There is no "lazy" mode for sscanf().

    You can use a basic (negated) character class to capture all non-dot character and prevent over-capturing.

    sscanf('foo.bar','%[^.].bar', $value);
    echo $value; //foo