2016-10-22 69 views
1

我只需要一個基本的簡單功能就可以做到。如何在PHP中評估數學公式(BODMAS)?

這裏是我的嘗試:

function parseEq($eq) { 
    $char = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; 
    $achar = array_map('ord', $char); 

    $eq = str_replace($char, $achar, $eq); 

    return eval(strtr('return {eq};', [ 
     '{eq}' => strtr($eq, [ 
      '=' => '==', 
     ]) 
    ])); 
} 

,但這個工程的僅一些例子:

var_dump(parseEq('2x = 2x')); 
var_dump(parseEq('a + b = b + a')); 
var_dump(parseEq('x - x = 0')); 
var_dump(parseEq('y/2 = (1/2)*y')); 
var_dump(parseEq('-(-x) = x')); 

但不是這2

var_dump(parseEq('2(x + y) = 2x + 2y')); 
var_dump(parseEq('2x = 2*x')); 

回答

1
<?php 
function parseEq($eq) { 
     $char = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; 
     $achar = array_map('ord', $char); 

     // debug 
     echo $eq . PHP_EOL; 

     $eq = str_replace($char, $achar, $eq); 

     // debug 
     echo $eq . PHP_EOL; 

     return eval(strtr('return {eq};', [ 
       '{eq}' => strtr($eq, [ 
         '=' => '==', 
       ]) 
     ])); 
} 

會產生

2x = 2x 
2120 = 2120 
bool(true) 
a + b = b + a 
97 + 98 = 98 + 97 
bool(true) 
x - x = 0 
120 - 120 = 0 
bool(true) 
y/2 = (1/2)*y 
121/2 = (1/2)*121 
bool(true) 
-(-x) = x 
-(-120) = 120 
bool(true) 
2(x + y) = 2x + 2y 
2(120 + 121) = 2120 + 2121 
PHP Parse error: syntax error, unexpected '(' in parseEq.php(16) : eval()'d code on line 1 
bool(false) 
2x = 2*x 
2120 = 2*120 
bool(false) 

所以它試圖替換每個信它就像x到120

有了一些修改

<?php 
function parseEq($eq) { 
    $char = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; 
    $achar = array_map('ord', $char); 

    echo $eq . PHP_EOL; 

    // replaceing 2(or 2x with 2* or 2*x 
    $eq = preg_replace('/(\d+)([\(a-z])/', "$1*$2", $eq); 
    echo $eq . PHP_EOL; 

    $eq = str_replace($char, $achar, $eq); 

    echo $eq . PHP_EOL; 

    return eval(strtr('return {eq};', [ 
     '{eq}' => strtr($eq, [ 
      '=' => '==', 
     ]) 
    ])); 
} 

普通值會產生

2x = 2x 
    2*x = 2*x 
    2*120 = 2*120 
    bool(true) 
    a + b = b + a 
    a + b = b + a 
    97 + 98 = 98 + 97 
    bool(true) 
    x - x = 0 
    x - x = 0 
    120 - 120 = 0 
    bool(true) 
    y/2 = (1/2)*y 
    y/2 = (1/2)*y 
    121/2 = (1/2)*121 
    bool(true) 
    -(-x) = x 
    -(-x) = x 
    -(-120) = 120 
    bool(true) 
    2(x + y) = 2x + 2y 
    2*(x + y) = 2*x + 2*y 
    2*(120 + 121) = 2*120 + 2*121 
    bool(true) 
    2x = 2*x 
    2*x = 2*x 
    2*120 = 2*120 
    bool(true) 

所以它現在的工作

+0

這是偉大的...如何做權力?像''(x^2)*(x^3)= x^5'' – user2707590

+0

http://php.net/manual/en/function.pow.php,它應該工作,如果你替換^與**(從PHP 5.6開始)。較低版本可以使用preg_replace將x^5更改爲pow(x,5) – Richard