note 45792 added to function.sscanf

From: Date: Sat, 18 Sep 2004 23:27:01 +0000
Subject: note 45792 added to function.sscanf
Groups: php.notes 
Request: Send a blank email to php-notes+get-76954@lists.php.net to get a copy of this message
The classic example <?php list($month, $day, $year) = sscanf($mandate, "%s %d %d"); ?> works fine if you already know the variable names you want to fill, and the format string you want to fill them with. If you want both of those to be dynamically configurable (as in reading a file with a flexible format), you may have a use for this code: Assumes your variables are listed in the variable $varstr = "var1, var2, var3" (you don't know what the variable names will be, perhaps they're a subset of a long list of valid ones) Assumes your input line is in $line, and your sscanf spec is in $spec. Both of these may also be in your input. Integrity checks omitted for clarity. <?php $vars = explode(',', $varstr); $values = @sscanf($line, $spec); // Do input integrity checks foreach ($vars as $var) { $var = trim($var); $next = each($values); $$var = $next['value']; if ($$var) $result_array[$var] = $$var; } ?> This took me some time to write successfully, so I'm including it for posterity. Non-obvious is the use of $next. Cheers, Steve ---- Manual Page -- http://www.php.net/manual/en/function.sscanf.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+45792 Delete -- http://master.php.net/manage/user-notes.php?action=delete+45792&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+45792&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#76954) next »