Search code examples
phpstringescapingscanfampersand

how to use php sscanf with ampersand character


I use php function sscanf to parse string and extrac parameters.

This code :

$s='myparam1=hello&myparam2=world';
sscanf($s, 'myparam1=%s&myparam2=%s', $s1, $s2);
var_dump($s1, $s2);

displays :

string(20) "hello&myparam2=world" NULL

but i would like string hello in $s1 and strin world in $s2.

Any help?


Solution

  • %s isn't an equivalent to \w in regexp: it doesn't pick up only alphanumerics

    $s='myparam1=hello&myparam2=world';
    sscanf($s, 'myparam1=%[^&]&myparam2=%s', $s1, $s2);
    var_dump($s1, $s2);
    

    but using parse_str() might be a better option for you in this case

    $s='myparam1=hello&myparam2=world';
    parse_str($s, $sargs);
    var_dump($sargs['myparam1'], $sargs['myparam2']);