[ad_1]
引用:输入特殊字符时如何显示错误消息,仅允许字母和空格
我尝试过的:
<!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>
[ad_2]
コメント