0

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

<?php

$string = "

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

<p>My name is <?php echo $var; ?></p>

";

?>

Then, when using the $string variable somewhere else, I want the code inside to be run properly as it should. The PHP code should run properly, also the HTML code should run properly. So, when echoing the $string, I will get My name is John wrapped in a <p> tag.

3
  • could you use a function and a heredoc? Commented Jan 24, 2015 at 13:11
  • You should probably just use an included file Commented Jan 24, 2015 at 13:14
  • You do not want to do this. This typically opens huge security holes. Commented Jan 24, 2015 at 13:18

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You're right about security. My client insisted like crazy in a feature which can be done only this way. He knows he's responsible for everything as long as it works. Thanks, I will try this.
1

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;
?>

Comments

0

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

<?php
    echo $string;
?>

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.