2012-03-17 50 views
5

我很努力地找到最好的方法來做到這一點。基本上我提供了這樣的字符串,用於打印出數學解析的字符串。PHP - 解析字符串內部的數學方程式

傑克通過測試的機會爲[0.8 * 100]%。凱蒂有一個[(0.25 + 0.1)* 100]%的機會。

數學方程總是用方括號括起來。爲什麼我要處理這樣的字符串是一個漫長的故事,但我真的很感激這種幫助!

+0

preg_match_all + eval + str_replace(或with preg_replace_callback)...依次。但要警告,eval可能是危險的,不要僅僅匹配[]或者有人可以在[]中添加代碼。 – Rufinus 2012-03-17 13:49:49

+0

雖然你可以'評估()'這些陳述,但這是一種安全風險。 – Robus 2012-03-17 13:51:48

回答

2
preg_match_all('/\[(.*?)\]/', $string, $out); 
foreach ($out[1] as $k => $v) 
{ 
    eval("\$result = $v;"); 
    $string = str_replace($out[0][$k], $result, $string); 
} 

此代碼是高度危險如果字符串用戶輸入,因爲它允許執行

+0

沒有用戶輸入,所以工作得很好。謝啦! – user949738 2012-03-17 14:04:10

-2

聲音,就像你的家庭作業....但無論如何。

你需要使用字符串操作php有很多內置函數,所以你很幸運。查看explode()函數和str_split()。

下面是具體涉及到的字符串函數的完整列表:http://www.w3schools.com/php/php_ref_string.asp

好運。

+0

不是作業......也許你從我虛構的例子中得到了這樣的印象? explode()是一個非常粗略的想法。 – user949738 2012-03-17 14:09:13

3

有大量的PHP數學庫評估的任何任意代碼。快速網絡搜索變成了this one


編寫自己的解析器也是一種選擇,如果它只是基本的算術應該不會太困難。隨着資源的存在,我會遠離這一點。


您可以採取更簡單的方法並使用eval。要小心先清理你的輸入。在eval docs's page上,有代碼的評論可以做到這一點。這裏有一個例子:

聲明:我知道eval只是一個邪惡的拼寫錯誤,這是一個可怕的可怕的事情,所有這一切。如果使用得當,它有用途,但。

<?php 

$test = '2+3*pi'; 

// Remove whitespaces 
$test = preg_replace('/\s+/', '', $test); 

$number = '(?:\d+(?:[,.]\d+)?|pi|π)'; // What is a number 
$functions = '(?:sinh?|cosh?|tanh?|abs|acosh?|asinh?|atanh?|exp|log10|deg2rad|rad2deg|sqrt|ceil|floor|round)'; // Allowed PHP functions 
$operators = '[+\/*\^%-]'; // Allowed math operators 
$regexp = '/^(('.$number.'|'.$functions.'\s*\((?1)+\)|\((?1)+\))(?:'.$operators.'(?2))?)+$/'; // Final regexp, heavily using recursive patterns 

if (preg_match($regexp, $q)) 
{ 
    $test = preg_replace('!pi|π!', 'pi()', $test); // Replace pi with pi function 
    eval('$result = '.$test.';'); 
} 
else 
{ 
    $result = false; 
} 

?> 
+0

我同意除了eval代碼示例(不適用於我)。 – davidmars 2015-02-28 06:59:27

0

從PHP doc示例更新了eval方法。

<?php 
function calc($equation) 
{ 
    // Remove whitespaces 
    $equation = preg_replace('/\s+/', '', $equation); 
    echo "$equation\n"; 

    $number = '((?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?|pi|π)'; // What is a number 

    $functions = '(?:sinh?|cosh?|tanh?|acosh?|asinh?|atanh?|exp|log(10)?|deg2rad|rad2deg|sqrt|pow|abs|intval|ceil|floor|round|(mt_)?rand|gmp_fact)'; // Allowed PHP functions 
    $operators = '[\/*\^\+-,]'; // Allowed math operators 
    $regexp = '/^([+-]?('.$number.'|'.$functions.'\s*\((?1)+\)|\((?1)+\))(?:'.$operators.'(?1))?)+$/'; // Final regexp, heavily using recursive patterns 

    if (preg_match($regexp, $equation)) 
    { 
     $equation = preg_replace('!pi|π!', 'pi()', $equation); // Replace pi with pi function 
     echo "$equation\n"; 
     eval('$result = '.$equation.';'); 
    } 
    else 
    { 
     $result = false; 
    } 
    return $result; 
} 
?>