Skip navigation.
Home

No Eval? Variable Interpolation on PHP Code

We recently turned off the websites' ability to use the eval() or related functions. In a small CMS I'd written a while back, I was using eval to interpolate variable names in strings. This was a simple way to do "lazy evaluation" on strings I was using as templates. With eval, there was no need to use a special templating syntax - the syntax was PHP's.

Now, with eval turned off, I needed a function to interpolate variables in a string. Here it is:

function interpolate( $string )
{
foreach ($GLOBALS as $name => $value)
{
$string = str_replace( '$'.$name, $value, $string );
}
$string = preg_replace( '/[$]\\w+/', '', $string );
return $string;
}

Reply

  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Allowed HTML tags: <a> <b> <dd> <dl> <dt> <i> <li> <ol> <u> <ul> <p> <br> <div> <pre> <code> <img><h1><h2><h3><h4> <blockquote>
  • Lines and paragraphs break automatically.

More information about formatting options