Skip to content Skip to sidebar Skip to footer

Run Php And Html Code From A String

I have a string stored in a variable in my php code, something like this:

My name is

Solution 1:

You don't want to do this. If you still insist, you should check eval aka evil function. First thing to know, you must not pass opening <?php tag in string, second you need to use single quotes for php script You want to evaluate (variables in single quotes are not evaluated), so your script should look something like:

<?php$string = '
<?php $var = "John"; ?>
<p>My name is <?php echo $var; ?></p>
';
// Replace first opening <?php in string$string = preg_replace('/<\?php/', '', $string, 1); 
eval($string);

However, this is considered very high security risk.

Solution 2:

So if I'm right, you have the $var = 'John'; stored in a different place.

Like this:

<?php$var = 'John'; ?>

And then on a different place, you want to create a variable named $String ? I assume that you mean this, so I would suggest using the following:

<?php$String = "<p>My name is ".$var." </p>";
    echo$String;
?>

Solution 3:

You should define $var outside the $string variable, like this

<?php$var="John";
$string = "<p>My name is $var</p>";

?>

Or you can use . to concatenate the string

<?php$var="John";
    $string = "<p>My name is ".$var."</p>";

    ?>

Both codes will return the same string, so now when doing

<?phpecho$string;
?>

You will get <p>My name is John</p>

Post a Comment for "Run Php And Html Code From A String"