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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.