Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I now have written an evaluator for your code, which addresses the circular reference problem, too.</p> <p>Use:</p> <pre><code>$expression = new Evaluator($vars); $vars['a'] = 'This is a string'; // ... $vars['circular'] = '%ralucric'; $vars['ralucric'] = '%circular'; echo $expression-&gt;evaluate('%circular'); </code></pre> <p>I use a <code>$this-&gt;stack</code> to handle circular references. (No idea what a stack actually is, I simply named it so ^^)</p> <pre><code>class Evaluator { private $vars; private $stack = array(); private $inEval = false; public function __construct(&amp;$vars) { $this-&gt;vars =&amp; $vars; } public function evaluate($str) { // empty string if (!isset($str[0])) { return ''; } if ($str[0] == '^') { $this-&gt;inEval = true; ob_start(); eval('$str = ' . preg_replace_callback('#%(\w+)#', array($this, '_replace'), substr($str, 1)) . ';'); if ($error = ob_get_clean()) { throw new LogicException('Eval code failed: '.$error); } $this-&gt;inEval = false; } else { $str = preg_replace_callback('#%(\w+)#', array($this, '_replace'), $str); } return $str; } private function _replace(&amp;$matches) { if (!isset($this-&gt;vars[$matches[1]])) { return $this-&gt;inEval ? 'null' : ''; } if (isset($this-&gt;stack[$matches[1]])) { throw new LogicException('Circular Reference detected!'); } $this-&gt;stack[$matches[1]] = true; $return = $this-&gt;evaluate($this-&gt;vars[$matches[1]]); unset($this-&gt;stack[$matches[1]]); return $this-&gt;inEval == false ? $return : '\'' . $return . '\''; } } </code></pre> <p><em>Edit 1</em>: I tested the maximum recursion depth for this script using this:</p> <pre><code>$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEF'; // GHIJKLMNOPQRSTUVWXYZ $length = strlen($alphabet); $vars['a'] = 'Hallo World!'; for ($i = 1; $i &lt; $length; ++$i) { $vars[$alphabet[$i]] = '%' . $alphabet[$i-1]; } var_dump($vars); $expression = new Evaluator($vars); echo $expression-&gt;evaluate('%' . $alphabet[$length - 1]); </code></pre> <p>If another character is added to <code>$alphabet</code> maximum recursion depth of 100 is reached. (But probably you can modify this setting somewhere?)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload