Created
July 9, 2014 02:03
-
-
Save szolotykh/8474d3928b63aadc5ddc to your computer and use it in GitHub Desktop.
Expression analysis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$operators=array("+","-","*","/"); | |
$numbers=array("0","1","2","3","4","5","6","7","8","9"); | |
$a=array(); | |
function findNodesFirst($exp,&$buff,&$nums,&$op){ | |
//Check $exp is empty? | |
$newExp=""; | |
$pos=0; | |
$q=0; | |
$p=false; | |
$nStart=0; | |
$nStop=0; | |
while($pos<strlen($exp)){ | |
if($exp[$pos]=="("){ | |
if($q==0){ | |
$nStart=$pos; | |
$newExp=$newExp.substr($exp,$nStop,$nStart-$nStop); | |
} | |
$q++; | |
$pos++; | |
continue; | |
} | |
if($exp[$pos]==")"){ | |
if($q==1){ | |
$nStart++; | |
$newExp=$newExp."NODE".findNodesFirst(substr($exp,$nStart,$pos-$nStart),$buff,$nums,$op); | |
$pos++; | |
$nStop=$pos; | |
} | |
$q--; | |
$pos++; | |
continue; | |
} | |
//Find numers | |
if($q==0){ | |
if(!$p&&in_array($exp[$pos],$nums)){ | |
$nStart=$pos; | |
$newExp=$newExp.substr($exp,$nStop,$nStart-$nStop); | |
$p=true; | |
$pos++; | |
if($pos==strlen($exp)){ | |
$nStop=$pos; | |
$nNum=count($buff); | |
$buff["NODE".$nNum]=$exp[$pos-1]; | |
$newExp=$newExp."NODE".$nNum; | |
$p=false; | |
} | |
continue; | |
}else{ | |
$flag=false; | |
if(($pos+1)==strlen($exp)){ | |
$flag=true; | |
$pos++; | |
}else{ | |
if(!(in_array($exp[$pos],$nums)||$exp[$pos]==".")){ | |
$flag=true; | |
}else{ | |
$pos++; | |
continue; | |
} | |
} | |
if($flag){ | |
$nStop=$pos; | |
$nNum=count($buff); | |
$buff["NODE".$nNum]=substr($exp,$nStart,$nStop-$nStart); | |
$newExp=$newExp."NODE".$nNum; | |
$pos++; | |
$p=false; | |
continue 1; | |
} | |
} | |
} | |
$pos++; | |
} | |
$nNum=count($buff); | |
$buff["NODE".$nNum]=$newExp; | |
return $nNum; | |
} | |
$str=findNodesFirst("15.18*789+(5872+7)+3203*((1+2+3.1)*(3+4))+(7-(70/(10+5)))*7781",$a,$numbers,$operators); | |
print_r($a); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment