note 54039 deleted from language.types.string by colder
| From: | colder@php.net | Date: | Tue, 17 Oct 2006 18:19:34 +0000 |
| Subject: | note 54039 deleted from language.types.string by colder | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-118645@lists.php.net to get a copy of this message | ||
Note Submitter: diannes at dbfields dot com
----
I was trying to perform a series of manipulations on a string and found that there doesn't
seem to be any easy way to force variable expansion to occur if a string hadn't originally been
created as double-quoted or heredoc. Maybe there's an easier workaround than the one below, but
it's what I ended up doing.
-------------------------------
$var = '5';
$str = "var = $var ";
echo $str; // prints 'var = "5" ' (expected result)
$str = 'var = "$var" ';
echo $str; // prints 'var = "$var" ' (expected result)
// NO VARIABLE EXPANSION:
$str = 'var = "$var" ';
echo $str; // prints 'var = "$var" '
echo "$str"; // prints 'var = "$var" '
$str = "$str";
echo $str; // still prints 'var = "$var" '
$str = (string)$str;
echo $str; // still prints 'var = "$var" '
$str = strval($str);
echo $str; // still prints 'var = "$var" '
// NO VARIABLE EXPANSION THIS WAY EITHER:
$str = 'var = "{$var}" ';
// yields similar results to above
// NO VARIABLE EXPANSION WHEN STRING IS FROM A FILE
$str = implode("",file("foo"));
echo $str; // prints 'var = "$var" '
// THIS WILL FORCE VARIABLE EXPANSION TO OCCUR:
$str = str_replace('"','\"',$str); // escape double quotes
echo eval('echo "'.$str.'";'); // prints 'var =
"5" '
$str = 'ob_start(); echo "'.$str.'"; ob_get_contents();';
$str = eval($str);
echo $str; // prints 'var = "5" '