【发布时间】:2017-06-26 07:24:11
【问题描述】:
我想弄清楚,如何使用 php 删除数学表达式中的括号。
有些情况是:
(A+B)(B+C) 应该保持不变
((((A)))) 应该得到 A
((A(B+C))) 应该得到 A*(B+C)
(((((B+C)*A)))) 应该得到 (B+C)*A
在任何情况下我都找不到正确的解决方案。使用诸如分配属性之类的数学规则是没有选择的。
我不是在寻找复制粘贴算法,只是一个适合我所有情况的标准。 这是最新的尝试,我尝试了正则表达式等不同的方法,但我没有弄明白。
function removeSurroundingBrackets($str)
{
$res=$str;
if(strcmp($res[0],'(')===0 && strcmp($res[strlen($res)-1],')')===0)
{
$firstOther=0;
for(; $firstOther<strlen($str);$firstOther++)
{
if(strcmp($str[$firstOther],'(')!==0)
break;
}
$removableCount=0;
$removableCount=substr_count($str,')',$firstOther)-substr_count($str,'(',$firstOther);
}
return substr($str,$removableCount,-$removableCount);
}
编辑:我找到了解决方案:
function removeSurroundingBrackets($str)
{
$res=$str;
while(strcmp($res[0],'(')===0 && strcmp($res[strlen($res)-1],')')===0)
{
if($this->checkBrackets(substr($res,1,-1)))
$res=substr($res,1,-1);
else
return $res;
}
return $res;
}
function checkBrackets($str)
{
$currdepth=0;
foreach(str_split($str) as $char)
{
if(strcmp($char,')')===0)
{
if($currdepth<=0)
return false;
else
$currdepth--;
}
else if(strcmp($char,'(')===0)
$currdepth++;
}
return true;
}
【问题讨论】:
-
请告诉我们您现在尝试了什么。你会用哪种方式去除括号?然后社区会帮助你。您可以使用正则表达式、字符串提取或或或...
-
使用正则表达式你可以试试something like this demo。
-
@bobblebubble:这是可能的,但不要使用
while和preg_match,您应该使用do...while和preg_replace的计数参数。 -
@CasimiretHippolyte 是的,好主意,谢谢!没有想过$count。所以你可以试试like this other demo @MartinB。
标签: php regex string parsing math