0

我有一个包含数学表达式的字符串,例如(21)*(4+2). (21)*(4+2) => 21*(4+2)出于计算的目的,我需要“简化”它,使其在表达式(即)之间不包含任何数字。我不知道该怎么做(我想到了一些用正则表达式替换的东西,但我不太擅长处理它)。

4

2 回答 2

0

好的,在我看来,我不小心解决了这个问题(到目前为止,preg_replace对我有用):

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

我认为它没有考虑小数。它生成的示例方程和输出位于codepad

对于小数,我[\d\.]+在正则表达式中使用了 a 。它似乎正在工作。

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

另一个链接

于 2013-02-21T17:19:03.420 回答
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.
}
于 2013-02-21T17:13:01.760 回答