How can multiple input fields be validated for allowed characters in PHP?

When validating multiple input fields for allowed characters in PHP, you can use regular expressions to define the pattern of acceptable characters. By using the preg_match function, you can check each input field against the defined pattern to ensure that only allowed characters are present. This helps to prevent any malicious or unwanted input from being submitted.

// Define the pattern for allowed characters
$pattern = '/^[a-zA-Z0-9\s.,!?-]*$/';

// Loop through each input field and validate against the pattern
foreach ($_POST as $input) {
    if (!preg_match($pattern, $input)) {
        // Invalid input detected, handle accordingly (e.g. display error message)
        echo "Invalid input detected. Please only use letters, numbers, spaces, and punctuation marks.";
        break;
    }
}