Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- ACT.PHP
- ini skrip action kalkulator dengan 1 input.
- */
- $i = 0;
- $ask = null;
- $return = null;
- if (isset($_GET['ask'])) {
- $ask = $_GET['ask'];
- echo $ask . " = ";
- }
- function math($ask)
- {
- $operator = array(
- "*" => "(\-?[0-9\.]+\*\-?[0-9\.]+)",
- "/" => "(\-?[0-9\.]+\/\-?[0-9\.]+)",
- "+" => "(\-?[0-9\.]+\+\-?[0-9\.]+)",
- "-" => "(\-?[0-9\.]+\-\-?[0-9\.]+)"
- );
- foreach ($operator as $key => $pattern) {
- for ($i=1; $i > 0 ; $i++) {
- if (preg_match($pattern,$ask)) {
- # code...
- preg_match($pattern,$ask,$result);
- $askx = preg_replace($pattern, "x", $ask);
- $asktmp = $result[0];
- /* menyelesaikan operasi dalam kurung */
- preg_match("/^\-?[0-9\.]+/",$asktmp,$nilai1);
- preg_match("/[0-9\.]+$/",$asktmp,$nilai2);
- $returntmp = null;
- if (preg_match("(\-?[0-9\.]+([^0-9\.]{2,2})[0-9\.]+)", $asktmp)) {
- $nilai2[0] = "-".$nilai2[0];
- }
- if ($key == "*") {
- $returntmp = $nilai1[0] * $nilai2[0];
- }
- if ($key == "/") {
- $returntmp = $nilai1[0] / $nilai2[0];
- }
- if ($key == "+") {
- $returntmp = $nilai1[0] + $nilai2[0];
- }
- if ($key == "-") {
- $returntmp = $nilai1[0] - $nilai2[0];
- }
- $ask = preg_replace("/(x)/", $returntmp, $askx);
- }
- else{break;}
- # code...
- }
- }
- return $ask;
- }
- // function
- function prepare($ask)
- {
- #do ()
- $i = 1;
- $pattern_kurung = "/\(([^\(\)]+)\)/";
- for ($i=1; $i > 0 ; $i++) {
- if (preg_match($pattern_kurung,$ask)) {
- preg_match($pattern_kurung,$ask,$result);
- $askx = preg_replace($pattern_kurung, "x", $ask);
- $asktmp = $result[1];
- /* menyelesaikan operasi dalam kurung */
- $returntmp = math($asktmp);
- $ask = preg_replace("/(x)/", $returntmp, $askx);
- // break;
- }
- else{
- return math($ask);
- break;
- }
- }
- }
- // check math syntax
- $pattern = "/^(\(*[\+\-]?\(*[\+\-]?\d+(.\d+)?\)*[\+\-\*\/]?)*$/i";
- if (!preg_match($pattern, $ask)==true) {
- $return = "math syntax is wrong!";
- }
- else{
- echo $return = prepare($ask);
- }
- header("location:index.php?return=".urlencode($return)."&ask=".urlencode($ask));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement