What are the potential pitfalls when using preg_replace in PHP for highlighting specific words in HTML content?
When using preg_replace in PHP to highlight specific words in HTML content, one potential pitfall is that it may not properly handle special characters within the content, leading to unexpected output or errors. To solve this issue, you can use the htmlspecialchars function to escape special characters before performing the preg_replace operation.
// HTML content with specific words to highlight
$html_content = "<p>This is a sample text with <strong>important</strong> keywords.</p>";
// Array of words to highlight
$words_to_highlight = array("important", "keywords");
// Escape special characters in the HTML content
$html_content_escaped = htmlspecialchars($html_content);
// Loop through each word to highlight and apply preg_replace with proper escaping
foreach ($words_to_highlight as $word) {
$html_content_escaped = preg_replace('/\b' . preg_quote($word, '/') . '\b/i', '<span style="background-color: yellow;">$0</span>', $html_content_escaped);
}
// Output the highlighted HTML content
echo $html_content_escaped;