2013-02-21 205 views
0

我有一個包含數學表達式的字符串,如(21)*(4+2)。爲了計算的目的,我需要「簡化」它,以便它不包含表達式之間的任何數字(即(21)*(4+2) => 21*(4+2))。我不知道該怎麼做(我想用正則表達式替換,但我不擅長處理它)。如何刪除字符串中不需要的括號?

+1

這是作業還是什麼?圍繞單個數字的括號不會改變表達式的結果。 – 2013-02-21 17:07:09

+1

嘗試像這樣'\(\ d + \)'匹配它們。如果匹配,請刪除括號。 – hjpotter92 2013-02-21 17:08:14

+0

我認爲該評論已被刪除。無論如何,這裏是一個例子鏈接http://codepad.org/pXQdiuak – hjpotter92 2013-02-21 17:13:46

回答

0

你可以做的算法是這樣的:

$str = "(21)*(4+2)"; 
//split above to array of characters 
$arr = str_split($str); 

foreach($arr as $i => $char) { 
    if character is opening parenthesis { 
    get all characters in a string until closing parnethesis is found 
    endif } 

    if the string you received from above contains only digits 
    (means it has no expression i.e. +,-,/,%,*) then remove the first and last 
    characters of the above string which are the parenthesis and append the 
    string to the final string. 
} 
+1

似乎比必要的更復雜。一個簡單的正則表達式替換可以很好地工作。 – nickb 2013-02-21 17:13:31

+0

這就是爲什麼這被稱爲使用算法:) – GGio 2013-02-21 17:14:09

0

好了,在我看來,我意外地解決了這個問題(到目前爲止,preg_replace作品對我來說):

echo preg_replace("/\((\d+)\)/", "$1", $eq); 

它不考慮小數,我想。它產生的樣本方程和輸出是here,在codepad

對於小數,我在正則表達式中使用了[\d\.]+。它似乎在工作。

echo preg_replace("/\(([\d\.]+)\)/", "$1", $eq); 

另一個link

相關問題