I agree w/ alimadzi. There are many problems w/ storing entire html/php code in a database and trying to parse it on the fly. If you have the CLI version of PHP installed you could probably open a pipe to it, send in your code and get the processed output. But this wouldn't work if you had say sessions or other CGI-specific parts in your code.
Another solution is to use eval as I did in the following code. You'd replace $mycode w/ whatever you SELECT from your database.
<?php
$mycode = "This is some text <?php \$GLOBALS['abc'] = 12; ?> <br> Value of global variable abc = <?php echo \$GLOBALS['abc']; ?>";
function evalAndGetOutput ($code) {
ob_start ();
eval (stripslashes ($code));
$output = ob_get_contents ();
ob_end_clean ();
return $output;
}
echo preg_replace ("/<\?php(.*)\?>/Use", "evalAndGetOutput ('\\1')", $mycode);
?>
Explanation: the evalAndGetOutput () function evaluates your PHP code and spits out whatever screen/stdout output it generates. The preg_replace uses the modifiers U (ungreedy, if you have more than one instance of <?php), s (if your code spans multiple lines), and e (which runs eval on the replacement so the function can get called).
There are many problems w/ doing something like above. First of all, you need to use $GLOBALS to declare global variables even if that part of the code is in the global scope. Second, if your PHP code in the DB contains any bugs or errors, it'll be hard to debug them (your logs will complain eval () failed and won't tell you exactly where it failed). Third, I'm not sure what the limitations of eval are, so I don't know if the above will work w/ objects, etc. Also, I don't know what the security related issues are, if any... unless of course you don't control what code is stored in your database (i.e. you let your users/visitors edit the html/php code you store).