How can you restrict input in a text field to only allow letters and numbers in PHP?

To restrict input in a text field to only allow letters and numbers in PHP, you can use a regular expression to validate the input. By checking if the input matches the pattern of only letters and numbers, you can ensure that any other characters are not accepted.

$input = $_POST['input_field'];

if (preg_match('/^[a-zA-Z0-9]*$/', $input)) {
    // Input contains only letters and numbers
    // Proceed with your code here
} else {
    // Input contains other characters
    echo "Input must contain only letters and numbers.";
}