What are the best practices for handling special characters and escape sequences in preg_replace patterns and replacements?

Special characters and escape sequences in preg_replace patterns and replacements can cause unexpected behavior or errors if not properly handled. To ensure that these characters are treated correctly, it is best practice to use the preg_quote() function to escape special characters in the pattern and use double backslashes to escape special characters in the replacement string.

$pattern = '/[a-z]/'; // pattern with special characters
$replacement = '123'; // replacement with special characters

$escaped_pattern = preg_quote($pattern, '/');
$escaped_replacement = preg_replace('/([{}])/', '\\\\$1', $replacement);

$result = preg_replace('/' . $escaped_pattern . '/', $escaped_replacement, $input_string);