I have an article stored in my database, and it is already marked up in HTML.
Then I have a PHP script which serves as a template and in it is the line…
echo $body;
What I would like to do is embed a Constant in the marked-up article in my database, and when I echo out the $body variable, the value of the Constant would appear.
Is there a way to do this?
If this was normal PHP I would do this…
echo "<p>Welcome to " . COMPANY . ", where the customer always comes first!";
But if I have this stored in my database…
<p>Welcome to " . COMPANY . ", where the customer always comes first!
or this…
<p>Welcome to COMPANY , where the customer always comes first!
That won’t make any difference. PHP stored as a string won’t be executed, it’ll just be output as text. To execute the code, you’d need to run the string through eval(), which is dangerous and definitely not a good idea.
A better solution might be to include some sort of tokens in the string, which you could parse and replace with the actual values after you retrieve the string from the DB.
As @fretburner noted, you want your stored template to contain a token that you can replace in PHP when you echo it. As long as you know what the replacements are meant to be when you’re echo’ing the code, something like this should help you.
$dbString = "<p>Welcome to %COMPANY% where the customer always comes first!</p>";
$tokenValues = [
"%COMPANY%" => $companyName
];
echo str_replace( array_keys($tokenValues), $tokenValues, $dbString);
Some notes on that. The % signs are there just to mark the start and end of the placeholders - this makes is easier to see where replacements are supposed to happen - there’s nothing special about the %s other than to make it less likely to replace something by accident.
Also, I used an array so that you can handle multiple replacements without having to call str_replace several times in your code. This, for example, might be relevant to want you’re hoping to achieve.
so first hello is replaced with goodbye, but since goodbye is already the result of a replacement it won’t be replaced again. Also, the replacements are better to read IMHO, in one associative array instead of two