What potential issues could arise when using str_replace to mark specific terms in a text, especially within HTML elements like H1-H6?

When using str_replace to mark specific terms in a text within HTML elements like H1-H6, the issue could arise when the search term appears within an HTML attribute or tag. This could result in unintended changes to the HTML structure and potentially break the layout or functionality of the page. To solve this issue, you can use a regular expression with preg_replace instead of str_replace to target specific text within the content while avoiding any HTML elements.

$content = "<h1>This is a heading with the term to mark</h1>";
$search_term = "term to mark";
$marked_content = preg_replace("/\b$search_term\b/", "<mark>$search_term</mark>", $content);
echo $marked_content;