Variable names in text?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
drock
Forum Newbie
Posts: 7
Joined: Fri Jun 14, 2002 12:49 pm
Location: Boulder, CO

Variable names in text?

Post by drock »

I'm storing text in a database field that is later pulled out using PHP and displayed in an html page. Basic "dynamic page" stuff so far. But I would also like to store variable names in the text and have those variable names replaced with their actual values which are set in PHP at the top of the page. Example text from database: "You have $vacdays days of vacation" would turn into "You have 21 days of vacation" if I set $vacdays=21 at the top of the page. Is there a way to do this other than search-and-replace?

Thanks you in advance for your response,
David Rock
Jim
Forum Contributor
Posts: 238
Joined: Fri Apr 19, 2002 5:26 am
Location: Near Austin, Texas

Post by Jim »

Just do what you did above:

You have $vacdays left of vacation.

if that doesn't work try:

You have '.$vacdays.' left of vacation.

:)
drock
Forum Newbie
Posts: 7
Joined: Fri Jun 14, 2002 12:49 pm
Location: Boulder, CO

Post by drock »

Unfortunately when I store that text in the database and pull it back out and display it, I'm seeing $vacdays or '.$vacdays.' (literally) rather than the current value of $vacdays from PHP. If I simply use: print "You have $vacdays days of vacation"; in my .php page, it works the way I want. But when I store that same text in a database then pull it out and assign it to $variablename and print $variablename; it does not convert $vacdays to the current value of $vacdays from PHP. There must be a slick way to do this...

Thanks
User avatar
amnuts
Forum Newbie
Posts: 16
Joined: Fri Jun 14, 2002 1:48 pm
Contact:

Post by amnuts »

Hi,

Use the 'eval' function on the string you returned from the database. See the PHP documentation for how to do this:

http://www.php.net/manual/en/function.eval.php

Andy
drock
Forum Newbie
Posts: 7
Joined: Fri Jun 14, 2002 12:49 pm
Location: Boulder, CO

Post by drock »

Eval worked great for me. I also had to use addslashes and stripslashes because of the html codes that are also in my text.

Thank you
Post Reply