Are there any specific PHP functions or methods that are recommended for highlighting search terms in text?

When highlighting search terms in text, one common approach is to use the PHP `preg_replace` function along with regular expressions to find and replace the search terms with a highlighted version of the term. By using a regular expression pattern that matches the search term, we can easily replace all occurrences of the term with a highlighted version.

function highlightSearchTerm($text, $searchTerm) {
    $highlightedTerm = "<span style='background-color: yellow'>$searchTerm</span>";
    return preg_replace("/\b$searchTerm\b/i", $highlightedTerm, $text);
}

$text = "This is a sample text where we will search for a specific term.";
$searchTerm = "sample";
$highlightedText = highlightSearchTerm($text, $searchTerm);

echo $highlightedText;