Echo CONSTANT in $text_var

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
User avatar
papa
Forum Regular
Posts: 958
Joined: Wed Aug 27, 2008 3:36 am
Location: Sweden/Sthlm

Echo CONSTANT in $text_var

Post by papa »

Hi,

I have a constant that I want to display within my content text.

Code: Select all

define("FEEDBACK", "mail to bla@bla.com for problems");
 
$text = "bla bla FEEDBACK bla bla;
But that just outputs FEEDBACK.

I've solved it by assigning a var to it ($feedback) and then write {$feedback} in the variable, which works.

Code: Select all

$feedback = FEEDBACK;
 
$text "bla {$feedback} yada yada";
But I want to skip that step and just be able to write it in the var.


thanks
User avatar
pcoder
Forum Contributor
Posts: 230
Joined: Fri Nov 03, 2006 5:19 am

Re: Echo CONSTANT in $text_var

Post by pcoder »

Replace your text with:

Code: Select all

 
$text="bla".FEEDBACK."yada yada";
 
It works.
filippo.toso
Forum Commoner
Posts: 30
Joined: Thu Aug 07, 2008 7:18 am
Location: Italy
Contact:

Re: Echo CONSTANT in $text_var

Post by filippo.toso »

You can't do it directly because there's no native way to make PHP expand constants within a double quoted string.

One solution is to use a code like the following:

Code: Select all

<?php 
define("FEEDBACK", "mail to bla@bla.com for problems");
 
$constants = get_defined_constants(true);
$constants = isset($constants['user']) ? $constants['user'] : array();;
foreach ($constants as $name => $value) {
    $$name = $value;
}
 
$text = "bla $FEEDBACK yada yada";
 
foreach ($constants as $name => $value) {
    unset($$name);
}
 
echo($text);
 
?>
An alternative is to implemente a string parser that checks for constants and replace them with the correct value.
User avatar
papa
Forum Regular
Posts: 958
Joined: Wed Aug 27, 2008 3:36 am
Location: Sweden/Sthlm

Re: Echo CONSTANT in $text_var

Post by papa »

Thank you both for quick responses.

I actually already had a string-parser for word symbols and scandinavian letters so just added /FEEDBACK/ to my preg_replace and it should do it. :)
Post Reply