GingerRobot Posted August 12, 2007 Share Posted August 12, 2007 Im trying to make a graphical calculator at the moment (yeah, i know it was 1st competition - didn't have the time or knowledge then) - and im currently working on a function to parse the equation. Im struggling a little with indices. Im trying to transform x^y into pow(x,y). What i have so far: <?php $eq = "6+4564.2151^145.63-3"; $eq = preg_replace("/(\+|\-|\*|\/)+(.*)\^(.*)(\+|\-|\*|\/)+/",'$1pow($2,$3)$4',$eq); echo $eq.'<br />'; $eq = "4564.2151^145.63"; $eq = preg_replace("/(\+|\-|\*|\/)+(.*)\^(.*)(\+|\-|\*|\/)+/",'$1pow($2,$3)$4',$eq); echo $eq.'<br />'; ?> Which produces output: 6+pow(4564.2151,145.63)-3 4564.2151^145.63 So, as you can see, the pattern works ok assuming that there are operators either side of the power expression, but if the only thing within the string is a power, then it doesn't work. I thought that by using the * quantifier(which is 0 or more as i understand) rather than the + quantifier, this would solve my problems: <?php $eq = "6+4564.2151^145.63-3"; $eq = preg_replace("/(\+|\-|\*|\/)*(.*)\^(.*)(\+|\-|\*|\/)*/",'$1pow($2,$3)$4',$eq); echo $eq.'<br />'; $eq = "4564.2151^145.63"; $eq = preg_replace("/(\+|\-|\*|\/)*(.*)\^(.*)(\+|\-|\*|\/)*/",'$1pow($2,$3)$4',$eq); echo $eq.'<br />'; ?> This gives: pow(6+4564.2151,145.63-3) pow(4564.2151,145.63) So, this works when there are no operators, but not when there are operators. I hope i've explained properly. Any help would be much appreciated. Ben Link to comment https://forums.phpfreaks.com/topic/64506-struggling-with-optional-subpattern/ Share on other sites More sharing options...
GingerRobot Posted August 12, 2007 Author Share Posted August 12, 2007 Hmm, ive just realise i need to re-think this anyway. My method(even if it worked!) would run into problems with negative numbers. Link to comment https://forums.phpfreaks.com/topic/64506-struggling-with-optional-subpattern/#findComment-321873 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.