What is the correct way to use regular expressions in PHP to validate a string for specific characters?

To validate a string for specific characters using regular expressions in PHP, you can use the preg_match function to check if the string contains only the allowed characters. You can define a regular expression pattern that includes the allowed characters and then use preg_match to test the string against that pattern. If the string matches the pattern, it means it contains only the allowed characters.

$string = "abc123"; // String to validate
$pattern = '/^[a-zA-Z0-9]*$/'; // Regular expression pattern for allowing only letters and numbers

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