How can str_replace() be used to highlight words in PHP and what precautions should be taken before implementation?

To highlight words in PHP using str_replace(), you can replace the target words with HTML tags for highlighting, such as <span style="background-color: yellow">word</span>. However, before implementing this, you should ensure that the input is sanitized to prevent XSS attacks by using functions like htmlspecialchars() or htmlentities().

&lt;?php
$input_text = &quot;This is a sample text with some words to highlight.&quot;;
$words_to_highlight = [&quot;sample&quot;, &quot;words&quot;];

foreach ($words_to_highlight as $word) {
    $input_text = str_replace($word, &#039;&lt;span style=&quot;background-color: yellow&quot;&gt;&#039; . $word . &#039;&lt;/span&gt;&#039;, $input_text);
}

echo $input_text;
?&gt;