What are the potential pitfalls of using preg_replace in PHP and how can they be mitigated?

One potential pitfall of using preg_replace in PHP is that it can be vulnerable to regex injection attacks if user input is directly passed into the pattern. To mitigate this risk, it is important to properly sanitize and validate user input before using it in a regular expression.

// Example of mitigating regex injection with preg_replace
$user_input = $_POST['user_input'];

// Validate and sanitize user input
$validated_input = preg_quote($user_input);

// Use the sanitized input in preg_replace
$output = preg_replace("/$validated_input/", "replacement_text", $string_to_search);