What potential pitfalls should be considered when using preg_match to validate strings in PHP?

One potential pitfall when using preg_match to validate strings in PHP is that the regular expression pattern may not be properly escaped, leading to unexpected results or vulnerabilities like code injection. To mitigate this risk, it is important to use the preg_quote function to escape any user input before using it in the regular expression pattern.

$user_input = $_POST['user_input']; // User input to validate

$escaped_input = preg_quote($user_input, '/'); // Escape user input

$pattern = '/^' . $escaped_input . '$/'; // Construct regular expression pattern

if (preg_match($pattern, $string_to_validate)) {
    // String is valid
} else {
    // String is not valid
}