What are the potential pitfalls of using preg_replace in PHP for search and replace operations?

One potential pitfall of using preg_replace in PHP for search and replace operations is that it can be vulnerable to regular expression injection if user input is not properly sanitized. To mitigate this risk, it is important to escape any user input that is used in the regular expression pattern. This can be done using the preg_quote function in PHP.

// Sanitize user input before using it in a regular expression pattern
$user_input = $_POST['user_input'];
$sanitized_input = preg_quote($user_input);

// Perform search and replace operation using sanitized input
$string = "Hello, world!";
$pattern = "/$sanitized_input/";
$replacement = "Goodbye";
$new_string = preg_replace($pattern, $replacement, $string);

echo $new_string;