PHP:如何在表单中输入二进制运算符+-*/%



我已经编写了一个基本的HTML/PHP来计算Cayley表,该表在具有n元素的有限集上进行一些基本的二进制运算。

文件名为q.php,代码(清除所有样式等)如下:

<!doctype html>
<html>
<head><meta http-equiv="content-type" content="text/html;"></head>
<body>
<form action="q.php" method="post">
    Order:&nbsp;<input type="number" name="c1"><br><br>
    Operation:&nbsp;<input type="text" name="c2"><br>
    (syntax:<strong>&nbsp;$i "+" $j "%" 3&nbsp;</strong>)<br><br>
    <input type="submit" name="submit" value="Calculate / Reset">
</form>
<?php
$n=$_POST['c1']; $p=$_POST['c2'];
echo "<table style="text-align: center; margin: auto;" cellpadding="8">n";
for ($i=0; $i<$n; $i++) {
    echo "<tr>n";
    for ($j=0; $j<$n; $j++) {
        eval("$a="$p";");
        echo "t<td>".$a."</td>n";
    }
    echo "</tr>n";
}
echo "</table>n";
?>
</body>
</html>

在表单中输入整数n非常容易,但(与这里完全一样)我找不到一个好的方法来在表单中键入二进制运算符(它们是字符串吗?)。

更准确地说,如果ij上的操作是例如i+(j mod 3),我想输入一些类似的内容

i + j % 3

甚至

$i + $j % 3

而不是

$i "+" $j "%" 3

后者带有双引号——对用户来说并不是很愉快——已经起作用了。

我们能做得更好吗?也许还可以管理括号(),像我已经做的i+(j*2)一样容易地计算(i+j)*2

我现在很好奇,谢谢!

试试这个

<?php
$n = $_POST['c1']; 
$p = trim(str_replace(' ', '', $_POST['c2'])); // Remove spaces

eval("$result = {$p};");
echo $result;
?>

最新更新