【解決方法】特殊文字入力時のエラーメッセージ


引用:

特殊文字が入力されたときにエラー メッセージを表示する方法。文字とスペースのみが許可されます。

私が試したこと:

<!DOCTYPE html>
<html>
<body>

    <?php
    
        if (isset($_POST['txt'])) {
        if (!empty($_POST['txt'])){
        $veggies = array("Potato", "Cucumber", "Carrot", "Orange", "Green Beans", "onion");
        $fruits  = array("Apple", "Banana", "orange", "Pineapple", "Grapes", "Watermelon");
        $salad   = array_merge ($veggies, $fruits);
        $Object = $_POST['txt'];
        $search = array_filter($salad, function($list) use ($Object) {
            return ( stripos($list, $Object) !== FALSE );
        });
        print_r($search);
        
        } 
    
   else {  
        echo 'Enter Item'; 
        
    }
    
    }
    
    ?>
    
                <form method="POST">
                    Search item:  <input type="text" name="txt" ><br> <br>
                                  <input type="submit">
                </form>
                 
</body>
</html>

解決策 2

PHP
if (isset($_POST['txt'])) {
    if (!empty($_POST['txt'])) {
        $input = $_POST['txt'];

        //Check for special characters
        if (preg_match('/^[a-zA-Z\s]+$/', $input)) {
            $veggies = array("Potato", "Cucumber", "Carrot", "Orange", "Green Beans", "onion");
            $fruits  = array("Apple", "Banana", "orange", "Pineapple", "Grapes", "Watermelon");
            $salad   = array_merge($veggies, $fruits);

            $search = array_filter($salad, function($list) use ($input) {
                return (stripos($list, $input) !== FALSE);
            });

            print_r($search);
        } else {
            echo 'Only letters and spaces are allowed.';
        }
    } else {  
        echo 'Enter an item.'; 
    }
}

数字も許可する場合は、正規表現 ‘ を使用できます。/^[a-zA-Z0-9\s]+$/「!」

解決策 4

これを試して:

<!DOCTYPE html>
<html>

<body>

    <?php
    if (isset($_POST['txt'])) {
        if (!empty($_POST['txt'])) {
            $veggies = array("Potato", "Cucumber", "Carrot", "Orange", "Green Beans", "Onion");
            $fruits  = array("Apple", "Banana", "Orange", "Pineapple", "Grapes", "Watermelon");
            $salad   = array_merge($veggies, $fruits);
            $Object = htmlspecialchars($_POST['txt']); // Sanitize user input
            $Object = strtolower($Object); // Convert to lowercase for case-insensitive search

            $search = array_filter($salad, function ($list) use ($Object) {
                return (stripos(strtolower($list), $Object) !== false);
            });

            print_r($search);
        } else {
            echo 'Enter Item';
        }
    }
    ?>

    <form method="POST">
        Search item: <input type="text" name="txt"><br> <br>
        <input type="submit">
    </form>

</body>

</html>

コメント

タイトルとURLをコピーしました