How can PHP functions like preg_replace and str_replace be utilized to highlight specific words in a text?

To highlight specific words in a text using PHP functions like preg_replace and str_replace, you can search for the target words and wrap them in HTML tags with a CSS class for styling. This can be achieved by using regular expressions with preg_replace to match the words and replace them with the highlighted version, or by using str_replace to directly replace the words with the highlighted version.

<?php
$text = "This is a sample text where we want to highlight certain words.";
$words_to_highlight = array("sample", "highlight");

foreach($words_to_highlight as $word) {
    $text = preg_replace("/\b($word)\b/i", "<span class='highlight'>$1</span>", $text);
}

echo $text;
?>