2013-02-21 206 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

相关问题