0

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?

Itay Grudev
  • 7,055
  • 4
  • 54
  • 86
TheFrancisOne
  • 2,667
  • 9
  • 38
  • 58

2 Answers2

0

%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']);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
0

How about using regular expressions?

Here is an example:

$string = 'myparam1=hello&myparam2=world';

// Will use exactly the same format
preg_match('/myparam1=(.*)&myparam2=(.*)/', $string, $matches); 
var_dump($matches); // Here ignore first result
echo("<br /><br />");

// Will match two values no matter of the param name
preg_match('/.*=(.*)&.*=(.*)/', $string, $matches); 
var_dump($matches); // Here ignore first result too
echo("<br /><br />");


// Will match all values no matter of the param name
preg_match('/=([^&]*)/', $string, $matches); 
var_dump($matches);

I all three cases the matches array will contain the params.

I'm pretty convinced that it's better. Good luck!

Itay Grudev
  • 7,055
  • 4
  • 54
  • 86