Q:

How to use eval() for php code stored in DB?

I have whole HTML code present in the db and it includes following HTML code-
<p class="card mb-4 shadow-sm"><img src="<?php echo SITE_URL; ?>/assets/images/blog/php.png" alt="php" title="php"></p>

This HTML is stored in db and I want it to print value of SITE_URL when it gets fetched because SITE_URL is dynamic (const here in this case).
I tried using PHP's own eval() function like the one mentioned in this article. But it's not working.
what would be the better way to do this OR
is there any other way to figure out this ?
Here, what I tried.
<p class="card mb-4 shadow-sm"><img src="<?php 
$str = SITE_URL;
eval('\$str = \'$str\';');
echo $str; ?>/assets/images/blog/php.png" alt="php" title="php"></p> 

A:

Presuming you know how dodgy using eval is..
As long as SITE_URL is defined, it would be fine. Then you would do something like:
<?php
define('SITE_URL', 'http://example.com');

$str = '<p class="card mb-4 shadow-sm"><img src="<?php echo SITE_URL; ?>/assets/images/blog/php.png" alt="php" title="php"></p>';

echo eval('?>'.$str);

https://3v4l.org/EEB54

An alternative to using eval, is to use a template and replace the placeholders with the values you define.
<?php
define('SITE_URL', 'http://example.com');

$vars = [
    'SITE_URL' => SITE_URL    
];

$template = '<p class="card mb-4 shadow-sm"><img src="{{ SITE_URL }}/assets/images/blog/php.png" alt="php" title="php"></p>';

// match any single word with _ or -, with spaces either side or not
// e.g: {{key}} or {{ key }} or {{key-foo}} or {{ key-foo }}
//  not {{ a b c }}
$str = preg_replace_callback("/{{[ ]{0,}([\w\_-]{1,})[ ]{0,}}}/", function ($match) use ($vars) {
    return array_key_exists($match[1], $vars) ? $vars[$match[1]] : '';
}, $template);

echo $str;

https://3v4l.org/cUK5B
Or look into using a template engine if you need more features.

