發現 MySQL 可直接計算字串運算式 (SELECT 1+2*3),避開 PHP 複雜解析器實作,支援數學函數、三角函數、對數指數等高級運算。
前端 (jQuery AJAX)
→ 後端 PHP (jsq1.php)
→ MySQL (SELECT 運算式)
→ 返回結果 → 前端顯示
<?php
$db = mysql_connect("localhost", "root", "123");
header("Content-Type: text/html; charset=GB2312");
$str = iconv('utf-8', 'gbk', trim($_POST['t_ask']));
$str = str_replace([" ", "\r\n", "(", ")"], ["", "", "(", ")"], $str);
// 三角函數轉換:MySQL 使用弧度,前端輸入角度
$str = preg_replace("/sin\((.*)\)/is", "sin(\${1}*pi()/180)", $str);
$str = preg_replace("/cos\((.*)\)/is", "cos(\${1}*pi()/180)", $str);
$str = preg_replace("/tan\((.*)\)/is", "tan(\${1}*pi()/180)", $str);
$str = preg_replace("/cot\((.*)\)/is", "1/tan(\${1}*pi()/180)", $str);
$str = preg_replace("/asin\((.*)\)/is", "asin(\${1})*180/pi()", $str);
$str = preg_replace("/acos\((.*)\)/is", "acos(\${1})*180/pi()", $str);
$str = preg_replace("/atan\((.*)\)/is", "atan(\${1})*180/pi()", $str);
$sql = "SELECT " . $str;
$res = mysql_query($sql, $db) or die('運算式錯誤');
$rs = mysql_fetch_array($res);
echo $rs[0];
?>
<html>
<head>
<title>手寫輸入計算器</title>
<script src="jquery.js"></script>
<script>
$(function(){
$("#t_ask").keyup(function(){
$.post("jsq1.php", { t_ask: $("#t_ask").val() }, function(data){
$("#res").html(data);
});
});
});
</script>
</head>
<body>
<h2>手寫輸入計算器</h2>
<textarea id="t_ask" cols="60" rows="6"></textarea>
<div id="res" style="font-size:24px; color:#006600;"></div>
<table>
<tr><td>支援函數:</td></tr>
<tr><td>sin/cos/tan/cot (角度)</td></tr>
<tr><td>asin/acos/atan (返回角度)</td></tr>
<tr><td>abs/ceil/floor/round</td></tr>
<tr><td>exp/log/pow/sqrt</td></tr>
<tr><td>pi()/rand()</td></tr>
</table>
</body>
</html>
| 分類 | 函數 | 範例 |
|---|---|---|
| 三角 | SIN, COS, TAN, COT, ASIN, ACOS, ATAN | SIN(PI()/2)=1 |
| 絕對/取整 | ABS, CEIL, FLOOR, ROUND | CEIL(1.1)=2 |
| 指數對數 | EXP, LOG, LOG10, LOG2, POW, SQRT | POW(2,10)=1024 |
| 常數 | PI() | PI()=3.14159... |
| 其他 | RAND, SIGN, MOD, DEGREES, RADIANS | DEGREES(PI())=180 |
eval() 但嚴格過濾字符白名單evalmath)