What are the best practices for validating and filtering input in PHP to ensure only allowed characters are present?

Validating and filtering input in PHP is crucial to prevent security vulnerabilities such as SQL injection and cross-site scripting attacks. To ensure only allowed characters are present in the input, you can use regular expressions to define a pattern of allowed characters and then validate the input against this pattern. Additionally, you can use PHP's filter_var function with FILTER_SANITIZE_STRING to remove any unwanted characters from the input.

// Define a regular expression pattern for allowed characters
$pattern = '/^[a-zA-Z0-9\s]+$/';

// Validate and filter the input
$input = $_POST['input'];
if (preg_match($pattern, $input)) {
    $filtered_input = filter_var($input, FILTER_SANITIZE_STRING);
    // Process the filtered input
} else {
    // Handle invalid input
}