What are common pitfalls when using preg_replace() with regular expressions in PHP?

Common pitfalls when using preg_replace() with regular expressions in PHP include not properly escaping special characters in the regular expression pattern, not using delimiters correctly, and not handling potential errors or warnings that may arise during the replacement process. To avoid these pitfalls, always escape special characters using preg_quote(), use appropriate delimiters such as '#' or '~', and handle errors using error handling functions like preg_last_error().

$pattern = '/\bword\b/';
$replacement = 'newword';
$string = 'Replace this word with newword';

if(preg_last_error() == PREG_NO_ERROR){
    $result = preg_replace('#' . preg_quote($pattern, '#') . '#', $replacement, $string);
    echo $result;
} else {
    echo 'Error during preg_replace: ' . preg_last_error();
}