note 56113 modified in function.eval by danbrown

From: Date: Tue, 25 Nov 2008 16:05:53 +0000
Subject: note 56113 modified in function.eval by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-146939@lists.php.net to get a copy of this message
This function will take any combination of HTML and (properly opened and closed)PHP that is given in a string, and return a value that is the HTML and the RESULT of that PHP code and return them both combined in the order that they were originally written. This is a correction of an earlier script. In the earlier varsion the preg_replace_callback search pattern was incorrect and wouldn't allow line breaks within the HTML sections. I have also included a line to change shorthand <?= $var ?> to <? echo $var; ?> This code is basicaly a version of the 'include' function which can be run on variables instead of files. Optionaly output can be captured using output buffering. <?php function eval_mixed_helper($arr){ return ("echo stripslashes(\"".addslashes($arr[1])."\");"); } function eval_mixed($string){ $string = "<? ?>".$string."<? ?>"; $string = preg_replace("/<\?=\s+(.*?)\s+\?>/", "<? echo $1; ?>", $string); $string = str_replace('?>', '', str_replace( array('<?php', '<?'), '', preg_replace_callback( "/\?>((.|\n)*?)<\?/","eval_mixed_helper",$string) ) ); return eval($string); } // output to browser eval_mixed($string); // output to variable ob_start(); eval_mixed($string); $final_html = ob_get_clean(); ?> --was-- This function will take any combination of HTML and (properly opened and closed)PHP that is given in a string, and return a value that is the HTML and the RESULT of that PHP code and return them both combined in the order that they were originally written. This is a correction of an earlier script. In the earlier varsion the preg_replace_callback search pattern was incorrect and wouldn't allow line breaks within the HTML sections. I have also included a line to change shorthand <?= $var ?> to <? echo $var; ?> This code is basicaly a version of the 'include' function which can be run on variables instead of files. Optionaly output can be captured using output buffering. <? function eval_mixed_helper($arr){ return ("echo stripslashes(\"".addslashes($arr[1])."\");"); } function eval_mixed($string){ $string = "<? ?>".$string."<? ?>"; $string = preg_replace("/<\?=\s+(.*?)\s+\?>/", "<? echo $1; ?>", $string); $string = str_replace('?>', '', str_replace( array('<?php', '<?'), '', preg_replace_callback( "/\?>((.|\n)*?)<\?/","eval_mixed_helper",$string) ) ); return eval($string); } // output to browser eval_mixed($string); // output to variable ob_start(); eval_mixed($string); $final_html = ob_get_clean(); ?> http://php.net/manual/en/function.eval.php

« previous php.notes (#146939) next »