What are some best practices for validating user input in PHP contact forms to ensure only alphanumeric characters are accepted for names?

To ensure only alphanumeric characters are accepted for names in PHP contact forms, one best practice is to use regular expressions to validate the input. This can be done by checking if the input matches the pattern of alphanumeric characters only. Additionally, it's important to sanitize the input to prevent any potential security vulnerabilities.

// Validate user input for name field to allow only alphanumeric characters
$name = $_POST['name'];

if (!preg_match('/^[a-zA-Z0-9 ]+$/', $name)) {
    // Invalid input, handle error
    echo "Invalid name input. Please enter only alphanumeric characters.";
} else {
    // Valid input, proceed with processing
    echo "Name input is valid: " . $name;
}