What are the best practices for using regular expressions in PHP to ensure accurate highlighting of words in HTML content?

When using regular expressions in PHP to highlight words in HTML content, it is important to properly escape special characters in the search term to avoid unintended behavior or errors. One way to achieve this is by using the preg_quote() function to escape the search term before using it in the regular expression pattern. This ensures that the search term is treated as a literal string and not as a part of the regular expression syntax.

<?php
// HTML content with the word to highlight
$html_content = "<p>This is a sample text with the word to highlight.</p>";

// Search term to highlight
$search_term = "word to highlight";

// Escape special characters in the search term
$escaped_search_term = preg_quote($search_term, '/');

// Regular expression pattern to match the search term
$pattern = '/\b(' . $escaped_search_term . ')\b/i';

// Highlight the search term in the HTML content
$highlighted_content = preg_replace($pattern, '<span style="background-color: yellow;">$1</span>', $html_content);

echo $highlighted_content;
?>