Take the 2-minute tour ×

I have a variable which calls content from database, sample is below

$content = '<div><h1>content here</h1>
<img src = 'image.jpg' /><br />

[code]echo 'welcome';[/code]

<h2>some content here</h2>
<p> some large content here</p>

[code]echo 'Click Here';[/code]

Thank you.';

echo 'headers here' .$content . 'footers here';

how can i execute PHP for the content in between [code] and [/code] tags? remaining text would written as html execpt the codes used in [code] some php code [/code] tags

share|improve this question
Don't! But seriously, why do you want to eval code from the db? I would avoid this kind of behaviour. Or perhaps i'm misunderstanding the question - are you trying to import and eval PHP code, or just dump some HTML into your page? –  Ryven Jul 20 '12 at 15:04
preg_replace() to find what's in between the tags, and then just eval() whatever it is. I'd highly advise against thist though. –  Louis Jul 20 '12 at 15:13
add comment

1 Answer

up vote 1 down vote accepted

If this is for a templateting type of system for your site I would suggest to go a different route.

First your above code would change so that the portion between you code would look like:


Now, you can still store your stuff in the database as php code if you want, but it makes more sense to eval it before you put it into the database, but I strongly suggest otherwise and go with a find/replace system.

Now, you would want to have a function that would do the following:

function output_template( $name, $data ) {
    $template_string = get_template_from_db( $name );
    for( $data as $k )
        $template_string = str_replace( $k, $data[$k], $template_string );
    return $template_string;

Then you can echo out the return value of this function. If you think you need to use eval, rethink what you are doing, especially for what appears to be a templating system.

share|improve this answer
add comment

Your Answer


