How can variables be properly masked in regular expressions using preg_quote() in PHP?

When using regular expressions in PHP, it is important to properly escape any variables that may contain special characters to prevent them from being interpreted as part of the regex pattern. This can be done using the preg_quote() function, which escapes all characters that have special meaning in regular expressions. By passing the variable through preg_quote(), you can ensure that it is treated as a literal string in the regex pattern.

$variable = "example.com";
$escaped_variable = preg_quote($variable, '/');
$pattern = '/^https?:\/\/' . $escaped_variable . '$/';

if (preg_match($pattern, $input)) {
    echo "Match found!";
} else {
    echo "No match found.";
}