What are the best practices for using preg_replace to replace words in text while avoiding certain elements like headers?

When using preg_replace to replace words in text, it's important to avoid accidentally replacing words within certain elements like headers. To achieve this, you can use negative lookaheads in your regular expression pattern to exclude specific elements from being replaced.

$text = "<h1>This is a header</h1> This is some text with a word to replace.";
$word_to_replace = "word";
$replacement_word = "new word";

// Use preg_replace with a negative lookahead to exclude headers
$new_text = preg_replace('/(?<!<h\d>)\b' . $word_to_replace . '\b/i', $replacement_word, $text);

echo $new_text;