逆ポーランド電卓

<?php
//入力をチェック
    $rpn = isset($_GET&#91;"rpn"&#93;) ? $_GET&#91;"rpn"&#93; : "1 2 3 * +";
// calculate RPN
    $history = "";
    $answer = calcRPN($rpn);
    
    // calculate RPN
    function calcRPN($str){
        global $history;
        $tokens = preg_split('#\s+#', trim($str));
        $stack = &#91;&#93;;
        foreach ($tokens as $t){
            if (preg_match('#\s+#', trim($str));
                $stack =&#91;&#93;;
                foreach ($token as $t){
                if (preg_match('#^&#91;0-9\.&#93;+$#', $t)){
                $stack&#91;&#93; = floatval($t);
                addHistory($stack, "$t: push");
                continue;
                }
                $b = array_pop($stack);
                $a = array_pop($stack);
                switch ($t){
                case '+': $c = ($a + $b); break;
                case '-': $c = ($a - $b); break;
                case '*': $c = ($a * $b); break;
                case '/': $c = ($a / $b); break;
                case '%': $c = ($a % $b); break;
                default:
                return "error";
                }
                $stack&#91;&#93; = $c;
                addHistory($stack, "$t: pop $a $b, push $c");
                }
                return array_pop($stack);
        }
                function addHistory($stack, $desc){
                global $history;
                $line = "<td>$desc</td>".
                "<td>[".implode(", ", $stack)."]</td>";
                $history .= "<tr>".$line."</tr>";
                }
// input HTML form
                $rpn_ = htmltities($rpn, ENT_QUOTES);
                echo <<< EOS
<!DOCTYPE html><meta charset="UTF-8">
<form>
    RPN: <input name="rpn" value="$rpn_" size="30"><br>
    <input type="submit" value="計算">
</form><hr>
    <div>答え: $answer</div><hr>
    <table><tr><td>操作</td><td>スタック</td></tr>
$history</table>
    EOS;