What are some best practices for validating a string in PHP to only allow specific characters like letters, numbers, and certain symbols?

When validating a string in PHP to only allow specific characters like letters, numbers, and certain symbols, you can use regular expressions to define the allowed characters and then check if the input string matches the pattern. This ensures that the input contains only the permitted characters and prevents any unwanted characters from being processed.

$input = "abc123$%^"; // Input string to validate
$pattern = "/^[a-zA-Z0-9$%^]+$/"; // Regular expression pattern to allow letters, numbers, $, %, and ^
if (preg_match($pattern, $input)) {
    echo "String is valid"; // Input string contains only allowed characters
} else {
    echo "Invalid characters found"; // Input string contains disallowed characters
}