How can regular expressions be used to restrict the input of special characters in PHP applications?

Regular expressions can be used to restrict the input of special characters in PHP applications by defining a pattern that allows only certain characters to be accepted. By using the preg_match function with the defined pattern, you can check if the input contains any special characters and handle it accordingly.

$input = "Hello!#123";
$pattern = '/^[a-zA-Z0-9 ]+$/'; // Only allows letters, numbers, and spaces

if (preg_match($pattern, $input)) {
    echo "Input is valid";
} else {
    echo "Input contains special characters";
}