What potential pitfalls should be considered when using preg_replace in PHP for string replacements?

One potential pitfall when using preg_replace in PHP for string replacements is the use of unescaped special characters in the replacement string, which can lead to unexpected results or errors. To avoid this, it is important to use the preg_quote function to escape any special characters in the replacement string before passing it to preg_replace.

$pattern = '/pattern/';
$replacement = 'replacement with $1 special characters';
$escaped_replacement = preg_quote($replacement, '/');
$result = preg_replace($pattern, $escaped_replacement, $input_string);