Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse variables in PHP string

Tags:

php

parsing

eval

NOTE: Eval is used here in total knowledge, the string parsed is entered by an administrator only, and the purpose is to store instructions in database, without restrictions to the instructions. If you have a good alternative, it is always appreciated, but don't just say "eval is bad".

I have a String in PHP, for example

$myString = "(35*$var1*64)/$var2";

I want to eval() this string, but before, I want to modify all the variables in the string like this:

$var2 -> $_POST['var2']

There may or may not be a blank space after the variable in $myString .

When I eval $myString, PHP throws an error "Undefined variable $var1". PHP read the string and parse the variables, so I guess there should be a way to parse all the variables in the string.

The output should be:

$myStringParsed = "(35*$_POST['var1']*64)/$_POST['var2']";

or an equivalent.

like image 768
Turtle Avatar asked Sep 25 '26 07:09

Turtle


1 Answers

Not maybe the best solution, but you can preprocess $_POST variable and generate $variablesString like this:

$variablesString = '';
foreach($_POST as $key => $val) {
    $variablesString .= '$' . $key . ' = ' . $val . ';' . PHP_EOL;
}

eval($variablesString . PHP_EOL . $myString)

For string support you can check if $val is string, and if yes - wrap it with quotes.

Second way

$myString = 'return (35 * $var1 * 64) / $var2;';
$re = "/\\$(\\w*)/im";

preg_match_all($re, $myString, $matches);

foreach($matches[1] as $match) {
    $search = '$' . $match;
    $replace = '$_POST[\'' . $match . '\']';
    $myString = str_replace($search, $replace, $myString);
}
echo eval($myString);

You can check it here

like image 68
Igor R Avatar answered Sep 27 '26 21:09

Igor R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!