What are the best practices for creating a filter in PHP that allows only certain characters like A-Z, a-z, 0-9, \n, \r, and \r\n?

When creating a filter in PHP to allow only certain characters like A-Z, a-z, 0-9, \n, \r, and \r\n, it is important to use regular expressions to match and filter out any unwanted characters. By using the preg_replace function with a regex pattern that allows only the specified characters, we can sanitize input strings and ensure they contain only the desired characters.

$input = "Hello, world! This is a test string with special characters \t and @.";
$filtered_input = preg_replace('/[^A-Za-z0-9\n\r]/', '', $input);

echo $filtered_input;