Page 1 of 1

Echo CONSTANT in $text_var

Posted: Thu Sep 25, 2008 2:25 am
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

Re: Echo CONSTANT in $text_var

Posted: Thu Sep 25, 2008 4:04 am
by pcoder
Replace your text with:

Code: Select all

 
$text="bla".FEEDBACK."yada yada";
 
It works.

Re: Echo CONSTANT in $text_var

Posted: Thu Sep 25, 2008 4:07 am
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.

Re: Echo CONSTANT in $text_var

Posted: Thu Sep 25, 2008 4:24 am
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. :)