How can the regex pattern in preg_match be modified to only allow specific characters in a string?

To only allow specific characters in a string using regex pattern in preg_match, you can specify those characters inside square brackets in the pattern. This will match only the characters specified within the brackets and reject any other characters. You can also use the negation "^" symbol inside the brackets to match any character except the ones specified.

$string = "abc123";
$pattern = "/^[a-z0-9]+$/i"; // Only allow letters (uppercase and lowercase) and numbers
if (preg_match($pattern, $string)) {
    echo "Valid string";
} else {
    echo "Invalid string";
}