如何删除字符串中不需要的括号?
问题描述:
我有一个包含数学表达式的字符串,如(21)*(4+2)
。为了计算的目的,我需要“简化”它,以便它不包含表达式之间的任何数字(即(21)*(4+2) => 21*(4+2)
)。我不知道该怎么做(我想用正则表达式替换,但我不擅长处理它)。如何删除字符串中不需要的括号?
答
你可以做的算法是这样的:
$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-21 17:07:09
尝试像这样'\(\ d + \)'匹配它们。如果匹配,请删除括号。 – hjpotter92 2013-02-21 17:08:14
我认为该评论已被删除。无论如何,这里是一个例子链接http://codepad.org/pXQdiuak – hjpotter92 2013-02-21 17:13:46