0

I'm currently trying to use PhP to "parse" user input. The page is just a form with one input field and the submit button.

The result I want to achieve is to make PhP echo(rand(0,100) if the user types "rand" But if the user types something of this form : "rand int1-int2" it echos "rand(int1,int2)"

I'm currently using switch, case, break for user input.

Thank you in advance !

<form action="<?php $_SERVER['PHP_SELF'] ?>" method="POST">
    <input type="text" name="commande" />
    <input type="submit" name="submit" value="envoyer!" />
</form>

<?php if (isset($_POST['commande'])) {

    switch($_POST['commande']){ 
        case "hello":
            echo"<h1> Hello </h1>";
        break;
        case substr($_POST['commande'], 0, 4)=="rand":
            echo(rand(1,100));
        break;
        }

    }
?>
2
  • So what progress have you made so far? Is it possible for you to pastebin what you have so far? Commented Apr 9, 2012 at 15:21
  • I added the code i have so far. Commented Apr 9, 2012 at 15:26

1 Answer 1

1

You can achieve this using explode.

<?php
    $input = 'rand 1245';
    list($command, $arguments) = explode(' ', $input);
    $arguments = explode('-', $arguments);
    switch($command) {
        case 'rand':
            print_r($arguments);break;
            $min = 0;
            $max = 100;
            if (count($arguments) == 2) {
                $min = (int)$arguments[0];
                $max = (int)$arguments[1];
            }

            echo rand($min, $max);
            break;

    }
?>

Live example

Sign up to request clarification or add additional context in comments.

5 Comments

Oh nice ! I understand how the code works, but how is it possible to combine it with the "switch", "case x", "break" form ? Thank you very much for your help !
I also forgot to ask something. What happens if the "delimiter" in the explode function doesn't exist ? Thx !
@AwakeZoldiek I've updated my code to use a switch statement. If the delimiter doesn't exist, it will just return the whole string, which is why you want to put checks in place like my if (count($arguments)...
I still have an error for the "random" input but I will figure this out later. Thanks for your help !
@AwakeZoldiek well if you can't solve it don't hesitate to ask. Maybe show me your code and the problem and I can help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.