You can try with this pattern:
$pattern = <<<'LOD'
~
#definitions
(?(DEFINE)
(?<sq> '(?:[^'\\]+|\\.)*+' ) # content inside simple quotes
(?<dq> "(?:[^"\\]+|\\.)*+" ) # content inside double quotes
(?<vn> [a-zA-Z_]\w*+ ) # variable name
(?<hndoc> <<< (["']?) (\g<vn>) \g{-2} \R # content inside here/nowdoc
(?: [^\r\n]+ | \R+ (?!\g{-1}; $) )*+
\R \g{-1}; \R
)
(?<cmt> /\* # multiline comments
(?> [^*]+ | \* (?!/) )*+
\*/
)
)
#pattern
<\?php \s+
(?: [^"'?/<]+ | \?+(?!>) | \g<sq> | \g<dq> | \g<hndoc> | \g<cmt> | [</]+ )*+
(?: \?> | \z )
~xsm
LOD;
Test:
$subject = <<<'LOD'
<h1>Extract the PHP Code</h1>
<?php
echo(date("F j, Y, g:i a") . ' and a stumbling block: ?>');
/* Another stumbling block ?> */
echo <<<'EOD'
Youpi!!! ?>
EOD;
echo(' that works.');
?>
<p>Some HTML text ...</p>
LOD;
preg_match_all($pattern, $subject, $matches);
print_r($matches);
Another way:
As mario suggests it in a comment, you can use the tokenizer. It's the most easy way to do that since you don't have to define anything, example:
$tokens = token_get_all($subject);
$display = false;
foreach ($tokens as $token) {
if (is_array($token)) {
if ($token[0]==T_OPEN_TAG) $display = true;
if ($display) echo $token[1];
if ($token[0]==T_CLOSE_TAG) $display = false;
} else {
if ($display) echo $token;
}
}