Jump to content

Struggling with optional subpattern


GingerRobot

Recommended Posts

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.