[ad_1]
Cita:Cómo mostrar un mensaje de error cuando se ingresan caracteres especiales, solo se permiten letras y espacios
Lo que he probado:
<!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>
Solución 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.'; } }
Si también permite números, puede utilizar la expresión regular ‘/^[a-zA-Z0-9\s]+$/‘!
Solución 4
Prueba esto:
<!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]
コメント