What are some ways to restrict input in a PHP form to only one word?
To restrict input in a PHP form to only one word, you can use regular expressions to validate the input. You can create a regular expression pattern that allows only one word, which means no spaces are allowed. By using the preg_match function in PHP, you can check if the input matches the specified pattern and only allow submission if it does.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$input = $_POST["input"];
// Regular expression pattern to allow only one word
$pattern = '/^\w+$/';
if (preg_match($pattern, $input)) {
// Input is valid, process the form
echo "Input is valid: " . $input;
} else {
// Input is not valid
echo "Input must be a single word with no spaces.";
}
}
?>
<form method="post">
<input type="text" name="input" />
<input type="submit" value="Submit" />
</form>