Expression Parser in PHP (tokens → AST → execution)
Within MILK ADMIN I created a fairly complex and complete expression parser. The system works in both PHP and JavaScript so that the same validations or calculations can be performed on both the server and client side. Since it's a fairly complex algorithm, here I present a brief example of how to build one because I find it a very interesting topic in the programming world
You can see the system in action here: Expression Parser
But what is an expression parser?
An expression parser converts a string into an array of tokens (numbers and operators) so they can then be executed in the correct order. In this article we will create a system that allows executing a mathematical equation while correctly handling operator precedence.
We have 3 steps to follow:
split a mathematical string into tokens (numbers and operators),
build a tree (AST) respecting precedence * / before + -,
and finally execute the AST to get the result.
At the end of the process we will have a file that allows executing simple mathematical operations like:
php parsing.php "2 + 3 * -4"
// Output: -10
What is an AST (Abstract Syntax Tree)
The most interesting concept in this article is the AST (Abstract Syntax Tree). An AST is a tree that represents the logical structure of an expression.
For example, for 2 + 3 * -4 the correct AST is structured like this:
at the root we have +, on the left 2, and on the right a * node
which in turn has 3 on the left and -4 on the right.
In our example the AST will be a nested array:
['op'=>'+', 'left'=>2, 'right'=>['op'=>'*', 'left'=>3, 'right'=>-4]]
It executes "from the leaves" meaning from the most nested expressions to the outermost ones. In practice the steps involve cycling through the array: if there's a number on the left it's fine, otherwise if there's an array the function is called recursively on its content. This will therefore be a recursive call. This way the multiplication will be executed first and then the addition.
This tree makes it clear that: first we do 3 * -4, then we do 2 + (result).
How we represent it here
In this exercise we use a very simple representation:
a number is a float (e.g. 2.0, -4.0),
while an operator node is a PHP array:
['op'=>'*', 'left'=>..., 'right'=>...]
This is an "exercise-style" form, so we will limit ourselves to operations. Remember that in mathematics multiplications and divisions are done before addition and subtraction.
Step 1 – Tokenize: from string to tokens
Objective: convert the string into an array like:
Input: "2 + 3 * -4"
Tokens: [2, '+', 3, '*', -4]
Key point: the "unary" minus
The minus sign can be binary (subtraction, e.g. 10 - 3)
or unary (sign of the number, e.g. -4, 2 * -3).
Rule used: - is unary if it's at the beginning, or if the previous token is an operator (+ - * /).
The tokenize function
function tokenize(string $s): array {
for($i = 0, $n = strlen($s), $t = []; $i < $n;) {
$c = $s[$i];
if($c === ' ') {
$i++;
continue;
}
if(ctype_digit($c) || ($c === '-' && (empty($t) || in_array(end($t), ['+','-','*','/'], true)))) {
$sgn = 1;
if($c === '-') {
$sgn = -1;
$i++;
}
for($num = ''; $i < $n && (ctype_digit($s[$i])||$s[$i] === '.');) $num .= $s[$i++];
if($num === '') throw new Exception("Invalid number");
$t[] = $sgn * (float)$num;
continue;
}
if(in_array($c,['+','-','*','/'], true)) {
$t[] = $c;
$i++;
continue;
}
$i++;
}
return $t;
}
This function returns an array with elements one after another: [2, '+', 3, '*', -4]
Step 2 – Parse: building the AST with level-based "collapse"
The "collapse" idea
We start from the linear tokens [ 2, '+', 3, '*', -4 ] and make two passes:
first we collapse * and /, then we collapse + and -.
Collapsing means: when you find an operator of the current level, instead of keeping the three values lhs op rhs in the list,
you replace them with an AST node: ['op'=>op, 'left'=>lhs, 'right'=>rhs].
// From:
[2, '+', 3, '*', -4]
// Becomes:
[2, '+', ['op'=>'*', 'left'=>3, 'right'=>-4]]
Why does it become exactly like this?
Inside collapseOps(nodes, ['*','/']): out starts with the first operand [2].
In the loop with pairs (op, rhs): in the first iteration op='+' and rhs=3 – the + is NOT in the set ['*','/'],
so we leave it as is: out = [2, '+', 3].
In the second iteration op='*' and rhs=-4 – the * is in the set, so we collapse:
lhs = pop(out) takes the last operand (3), we create the node and put it back in out.
The final list after the * / pass is: [ 2, '+', (3 * -4) ].
At this point you don't have the complete tree yet, but you've already "packaged" the multiplications/divisions into AST nodes.
A second pass will be needed to collapse + and -.
collapseOps (compact)
function collapseOps(array $nodes, array $ops): array {
if(empty($nodes)) return [];
for($out = [$nodes[0]], $i = 1, $n = count($nodes); $i < $n; $i += 2){
$op = $nodes[$i]; $rhs = $nodes[$i+1] ?? null;
if($rhs === null) throw new Exception("Missing operand after '$op'");
if(in_array($op, $ops, true)){
$lhs = array_pop($out);
$out[] = ['op' => $op,'left' => $lhs,'right' => $rhs];
} else {
$out[] = $op;
$out[] = $rhs;
}
}
return $out;
}
parse (compact)
function parse(array $t): array {
$t = collapseOps($t, ['*', '/']);
$t = collapseOps($t, ['+', '-']);
if(count($t) !== 1) throw new Exception("AST not reduced to 1 node");
return $t[0];
}
Step 3 – Executing the AST (recursive evaluation)
The execute(node) function does: if node is a number, return that number;
if node is an array with op/left/right, recursively execute left and right,
then apply the operator.
Compact code (execute)
function execute($node) {
// Is it a number? Return it
if (is_numeric($node)) {
return $node;
} else if ($node == null) {
return 0;
}
// Is it an array? Go deeper
$left = execute($node['left']);
$right = execute($node['right']);
// Now I have two numbers, calculate
return match($node['op']) {
'+' => $left + $right,
'-' => $left - $right,
'*' => $left * $right,
'/' => $left / $right,
};
}
Execution example
To run it from the terminal:
if (count($argv) == 1) {
echo "No arguments provided, please provide arguments\n";
} else {
$string = implode(" ", array_slice($argv, 1));
$tokens = tokenize($string);
$result = parse($tokens);
echo "AST: ";
print_r($result);
$result = execute($result);
echo "Result: $result\n";
}
Output:
php parsing.php "2 +3 *-4"
Tokens: 2 + 3 * -4
AST: Array
(
[op] => +
[left] => 2
[right] => Array
(
[op] => *
[left] => 3
[right] => -4
)
)
Result: -10
These reflections come from developing MilkAdmin, a PHP admin panel system that I actively maintain. Code, demo and documentation are available at milkadmin.org. MIT License.