找不到显示匹配?

时间:2018-04-17 06:58:36

标签: php html

        <?php
            $nameErr = "";
            if(isset($_POST["name"])){ //Check form submission
                $name = test_input($_POST["name"]);
                if (!preg_match("/^[a-zA-Z ]*$/",$name)) {//Check Validations
                   echo  "Only letters allowed"; 
                }
                elseif(empty($_POST["name"])){
                    echo "No letter entered";//Check not empty name
                }
                else { 
                    $veggies = array("Potato", "Cucumber", "Carrot", "Orange", "Green Beans", "onion");
                    $fruits  = array("Apple", "Banana", "orange", "Pineapple", "Grapes", "Watermelon");
                    $salad   = array_merge ($veggies, $fruits);
                    $Object = $_POST["name"];
                    $search = array_filter($salad, function($list) use ($Object){
                        return ( stripos($list, $Object) !== FALSE );
                    });
                    print_r($search); //displays the result
                } 

            }
            function test_input($data) {
                $data = htmlspecialchars($data);
                return $data;
            }
        ?>
        <!DOCTYPE HTML>
        <html>
            <body>
               <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
                    Enter Letter: <input type="text" name="name"><span> <?php echo $nameErr;?></span><br><br>
                    <input type="submit" name="submit" value="Submit">
                </form>
            </body>
        </html>

如果我输入“aaaaaa”并且这些元素不在数组中,那么它应该显示未找到的匹配,我在isset语句中使用in_array但它不起作用,是正确的方法还是错误?

1 个答案:

答案 0 :(得分:0)

<?php
    $nameErr = "";
    if(isset($_POST["name"])){ //Check form submission
    $name = test_input($_POST["name"]);

    if (!preg_match("/^[a-zA-Z ]*$/",$_POST["name"])) {//Check Validations
        echo  "Only letters allowed"; 
    } elseif(empty($_POST["name"])) {
        echo "No letter entered";//Check not empty name
    } else { 
      $veggies = array("Potato", "Cucumber", "Carrot", "Orange", "Green Beans", "onion");
      $fruits  = array("Apple", "Banana", "orange", "Pineapple", "Grapes", "Watermelon");
      $salad   = array_merge ($veggies, $fruits);

      if (in_array($_POST["name"], $salad)) {
            echo 'matches found';
       } else {
            echo 'matches not found';
       }
    }



     function test_input($data) {
                    $data = htmlspecialchars($data);
                    return $data;
     }
?>

尝试这样的事情