How can special characters be allowed in a PHP string while restricting certain characters?

Special characters can be allowed in a PHP string by using a regular expression to check for the presence of allowed characters while restricting certain characters. One way to achieve this is by using the preg_replace() function to remove any characters that are not on the allowed list.

// Define the allowed characters in the string
$allowed_characters = '/^[a-zA-Z0-9!@#$%^&*()_+-=,.<>?;:{}\[\]\'"\/\\\|~` ]+$/';

// Input string with special characters
$input_string = "Hello, this is a string with special characters!@#";

// Remove any characters that are not on the allowed list
$cleaned_string = preg_replace('/[^a-zA-Z0-9!@#$%^&*()_+-=,.<>?;:{}\[\]\'"\/\\\|~` ]/', '', $input_string);

echo $cleaned_string;