To find a method of judging the familiar regular
I wrote a function.
Autoconv ($string, $a =array ())
{
Eval (' $res = '. $string. '; ');
return ($res);
}
The function is automatically calculated based on the expression of the string, where $array is more special, and the string expression may contain array elements.
Like what:
Autoconv (' a[1]+a[2]-a[3] ', Array (0,10,20,30))
return result 10+20-30 = 0
Wordy so much, I hope you see, here is a question to judge, is passed over the string expression whether there are unassigned elements.
Like what:
Autoconv (' a[1]+a[2]-a[3]+a[4] ', Array (0,10,20,30))
Where there is no a[4] value
In fact, this function is to process the data read in the database, and according to the first parameter string expression to calculate, if encountered no assignment, just read the database separately
Because of the whole system design, sometimes it is inevitable that the default passed array does not contain all the array elements required by the string expression, this time need to determine which value is not, and then read the database alone, and this judgment I can not write, thank you for your help ~!
Like what
' (a[1]+a[2])/2 * a[3]-a[4] ' Such a string expression, have a[1] a[2] a[3] a[4] Such 4 parameters, how to judge out, thank you!!
------Solution--------------------
If there is a nesting, the analysis is very difficult
That's not okay.
Ob_start ();
Eval ("...");
$res = Ob_get_contents ();
Ob_clean ();
Determine if there is any error message in $res
------Solution--------------------
Is that what it means?
PHP code
function autoconv ($string, $a =array ()) {Preg_match_ All ('/\[(\d+) \]/', $string, $r); $t = Array_diff ($r [1], Array_keys ($a)); if ($t) return ' missing data item: '. Join (', ', $t); $string = Str_replace (' A ', ' $a ', $string); Eval (' $res = '. $string. '; '); return ($res);}
------Solution--------------------
PHP code
//the door to get an axe, Fu. Nction Auto () {$arg =func_get_args (); Preg_match_all ("/(%d)/i", $arg [0], $rs); $parttern = $arg [0]; Array_shift ($arg); $arglist =join (",", $arg); Eval ("\ $string =sprintf (' $parttern ', $arglist);"); Eval ("Echo $string;"); } auto ("%d*%d*%d-%d", 1,2,9,4); Auto ("%d*%d*%d-%d", 10,2,9,4);