How can htmlspecialchars() be used to prevent HTML validation issues when replacing text within HTML tags in PHP?

When replacing text within HTML tags in PHP, using the htmlspecialchars() function can prevent HTML validation issues by encoding special characters like <, >, and &. This ensures that the replaced text does not interfere with the structure of the HTML document.

$text = &quot;&lt;p&gt;Hello, &lt;strong&gt;World&lt;/strong&gt;&lt;/p&gt;&quot;;
$replacement = &quot;Everyone&quot;;
$encoded_text = htmlspecialchars($text, ENT_QUOTES, &#039;UTF-8&#039;);
$encoded_replacement = htmlspecialchars($replacement, ENT_QUOTES, &#039;UTF-8&#039;);
$new_text = str_replace($encoded_text, $encoded_replacement, $text);
echo $new_text;