What potential issue arises when using str_replace to highlight specific text in PHP?
When using str_replace to highlight specific text in PHP, a potential issue is that it may replace text within HTML tags, which can break the structure of the HTML. To solve this issue, you can use a regular expression with preg_replace instead of str_replace to ensure that only text outside of HTML tags is replaced.
$text = "This is an example text with <b>bold</b> and <i>italic</i> tags.";
$highlighted_text = "bold";
$pattern = "/(?<!<[^>]*)\b" . preg_quote($highlighted_text, "/") . "\b(?![^<]*>)/i";
$replacement = "<span style='background-color: yellow;'>$0</span>";
$highlighted_text = preg_replace($pattern, $replacement, $text);
echo $highlighted_text;