How can HTML content with embedded PHP code be properly parsed and extracted in PHP?

When parsing HTML content with embedded PHP code in a PHP script, the PHP code within the HTML needs to be properly extracted and executed. One way to achieve this is by using PHP's `preg_match_all` function to extract the PHP code from the HTML content and then using `eval` to execute the extracted PHP code.

$htmlContent = '<html><body><?php echo "Hello, World!"; ?></body></html>';

preg_match_all('/<\?php(.*?)\?>/s', $htmlContent, $matches);

foreach ($matches[1] as $phpCode) {
    eval($phpCode);
}