What are some common pitfalls when using the preg_replace function in PHP?

One common pitfall when using the preg_replace function in PHP is not properly escaping special characters in the regular expression pattern. This can lead to unexpected results or errors in the replacement process. To solve this issue, it is important to use the preg_quote function to escape any special characters in the pattern before using it in preg_replace.

$pattern = '/[.*]/'; // pattern with special characters
$replacement = 'replacement';
$subject = 'This is a [test] string';

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

echo $result;