How can PHP developers ensure that special characters and spaces are not allowed in user input?

To ensure that special characters and spaces are not allowed in user input, PHP developers can use regular expressions to validate the input. By defining a regular expression pattern that only allows alphanumeric characters, developers can check if the user input meets the criteria and reject any input that contains special characters or spaces.

$userInput = $_POST['user_input'];

if (preg_match('/^[a-zA-Z0-9]+$/', $userInput)) {
    // User input is valid and does not contain special characters or spaces
    // Proceed with processing the input
} else {
    // User input contains special characters or spaces
    // Display an error message or take appropriate action
}