How can PHP code be extracted and highlighted from a string?

To extract and highlight PHP code from a string, you can use regular expressions to search for PHP code patterns within the string. Once the PHP code is identified, you can apply syntax highlighting by wrapping it in HTML tags with a specific class for styling. This approach allows you to separate and style the PHP code within the string effectively.

<?php
$string = "This is some PHP code: <?php echo 'Hello, World!'; ?>";
$pattern = '/<\?php(.*?)\?>/s';
preg_match_all($pattern, $string, $matches);

foreach ($matches[0] as $match) {
    $highlighted_code = "<span class='php-code'>" . htmlentities($match) . "</span>";
    $string = str_replace($match, $highlighted_code, $string);
}

echo $string;
?>