note 108091 deleted from function.eval by googleguy
| From: | googleguy@php.net | Date: | Fri, 24 Feb 2017 21:10:43 +0000 |
| Subject: | note 108091 deleted from function.eval by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-208818@lists.php.net to get a copy of this message | ||
Note Submitter: sc1n at yahoo dot com
----
If you would like to handle doing an eval on a string with mixed PHP and other stuff such as HTML,
you can use the following:
Example:
<?php
$test_string = 'A friendly llama <?php 1 == 1 ? "spit on" : "hugged";
?> me';
$p = new PhpStringParser();
echo $p->parse($mixed_string);
?>
Result:
A friendly llama spit on me
You can optionally make variables that are outside of the string you are parsing available to the
eval level scope by passing them into the constructor.
Example:
<?php
$llama_action = 'hugged';
$test_string = 'A friendly llama <?=$llama_action?> me';
$p = new PhpStringParser(array('llama_action', $llama_action));
echo $p->parse($mixed_string);
?>
Result:
A friendly llama hugged me
<?php
class PhpStringParser
{
protected $variables;
public function __construct($variables = array())
{
$this->variables = $variables;
}
protected function eval_block($matches)
{
if( is_array($this->variables) && count($this->variables) )
{
foreach($this->variables as $var_name => $var_value)
{
$$var_name = $var_value;
}
}
$eval_end = '';
if( $matches[1] == '<?=' || $matches[1] == '<?php=' )
{
if( $matches[2][count($matches[2]-1)] !== ';' )
{
$eval_end = ';';
}
}
$return_block = '';
eval('$return_block = ' . $matches[2] . $eval_end);
return $return_block;
}
public function parse($string)
{
return preg_replace_callback('/(\<\?=|\<\?php=|\<\?php)(.*?)\?\>/',
array(&$this, 'eval_block'), $string);
}
}
?>