How can special characters be escaped in regular expressions in PHP?

Special characters in regular expressions can be escaped in PHP by using the backslash "\" before the special character. This tells PHP to treat the special character as a literal character rather than a part of the regular expression syntax. This is useful when you want to search for a specific special character in a string using a regular expression.

$pattern = '/\$[0-9]+/'; // Search for a dollar sign followed by one or more digits
$string = 'I have $100 in my wallet.';
if (preg_match($pattern, $string)) {
    echo 'Found a match!';
} else {
    echo 'No match found.';
}