What best practices should be followed when using preg_replace in PHP to avoid errors or unexpected results?

When using preg_replace in PHP, it is important to properly escape special characters in the regular expression pattern to avoid errors or unexpected results. This can be achieved by using the preg_quote function to escape any characters with special meaning in regular expressions.

$pattern = '/[.*]/'; // pattern with special characters
$escaped_pattern = preg_quote($pattern, '/'); // escape special characters
$replacement = 'replacement_text';
$string = 'input_string';

$result = preg_replace('/' . $escaped_pattern . '/', $replacement, $string);