What are some best practices for handling unknown modifiers in preg_replace functions in PHP to prevent errors?

When using preg_replace in PHP, it is important to handle unknown modifiers to prevent errors. One way to do this is by using the preg_quote function to escape any potential modifiers in the pattern string before passing it to preg_replace. This ensures that the pattern is treated as a literal string and not interpreted as a regular expression modifier.

$pattern = '/example/i'; // pattern with potential modifiers
$replacement = 'replacement';
$subject = 'This is an example';

$escaped_pattern = preg_quote($pattern, '/');
$result = preg_replace('/' . $escaped_pattern . '/', $replacement, $subject);
echo $result;