Tuesday, April 6, 2010

Eval string with PHP tags

Here is another non-obvious twist on PHP.

I have been trying to evaluate tags in a php string without having to run preg_match or do any other kind of parsing. So I read some articles that propose this:

eval('?>' . $sMyStringWithPHPTagsInIt . '<?');

This works, since eval implicitly opens up php tags around evaluated code.
However, it outputs the result to the STDOUT. This is not helpful when you need to do additional operations on the string after the evaluation.

So, I came up with this:

function evalFile($sFileName) {
 ob_start();
 ob_flush();
 eval('?>' . file_get_contents($sFileName) . '<?');
 $s = ob_get_contents();
 ob_clean();
 return $s;  
}

It grabs the buffer from STDOUT and returns it into a string. The only problem is that it would have to flush the current contents of the buffer. If someone has a better solution, please post it here.