note 108091 added to function.eval
| From: | sc1n at yahoo dot com | Date: | Wed, 28 Mar 2012 00:57:51 +0000 |
| Subject: | note 108091 added to function.eval | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-186882@lists.php.net to get a copy of this message | ||
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);
}
}
?>
----
Server IP: 64.71.164.2
Probable Submitter: 70.113.52.110
----
Manual Page -- http://www.php.net/manual/en/function.eval.php
Edit -- https://master.php.net/note/edit/108091
Del: integrated -- https://master.php.net/note/delete/108091/integrated
Del: useless -- https://master.php.net/note/delete/108091/useless
Del: bad code -- https://master.php.net/note/delete/108091/bad+code
Del: spam -- https://master.php.net/note/delete/108091/spam
Del: non-english -- https://master.php.net/note/delete/108091/non-english
Del: in docs -- https://master.php.net/note/delete/108091/in+docs
Del: other reasons-- https://master.php.net/note/delete/108091
Reject -- https://master.php.net/note/reject/108091
Search -- https://master.php.net/manage/user-notes.php