How can PHP functions like preg_match be utilized to check if user input contains only certain characters, such as letters or numbers?

To check if user input contains only certain characters, such as letters or numbers, we can use PHP functions like preg_match with regular expressions. We can define a regular expression pattern that specifies the allowed characters, then use preg_match to check if the user input matches that pattern. If the input contains any characters outside of the specified range, the preg_match function will return false.

$input = "abc123"; // User input to be checked
$pattern = '/^[a-zA-Z0-9]+$/'; // Regular expression pattern to allow only letters and numbers

if (preg_match($pattern, $input)) {
    echo "Input contains only letters and numbers.";
} else {
    echo "Input contains invalid characters.";
}