How can PHP be used to highlight specific text within a string while ignoring HTML tags?

When highlighting specific text within a string in PHP, we need to ensure that HTML tags are not affected by the highlighting process. One way to achieve this is by using regular expressions to match the text while ignoring any HTML tags present in the string. By using the `preg_replace()` function with a regular expression pattern that excludes HTML tags, we can highlight the desired text without affecting the HTML structure of the string.

function highlightText($text, $search) {
    $pattern = "/$search(?![^<]*>)/i";
    $replacement = "<span style='background-color: yellow;'>$0</span>";
    return preg_replace($pattern, $replacement, $text);
}

// Example usage
$text = "<p>This is a <strong>sample</strong> text with <em>HTML</em> tags.</p>";
$search = "sample";
$highlightedText = highlightText($text, $search);
echo $highlightedText;