note 90241 added to language.types.string
| From: | strata_ranger at hotmail dot com | Date: | Sun, 12 Apr 2009 00:31:09 +0000 |
| Subject: | note 90241 added to language.types.string | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-153101@lists.php.net to get a copy of this message | ||
A limitation of the 'complex' parsing of double-quoted strings (i.e. with curly braces) is
that since you can't escape curly braces, if for some reason you need a parsed variable
surrounded by literal curly braces, you can't do this directly.
For example, say want to dynamically compile some Javascript for the client's browser:
<?php
// Here's the array we start with.
$array = Array(0=>'foo', 1=>'bar');
// This is how the same array would look in Javascript:
// var my_array = {0:'foo', 1:'bar'}
// This is how we'll convert it to the Javascript representation
$values = Array();
foreach($array as $key=>$string) $values[] = sprintf("%d:'%s'", $key,
addcslashes($string, "'"));
$values = implode(',' , $values); // $values is now = "0:'foo',
1:'bar'"
// Begin echoing the Javascript
echo "<script type='text/javascript'>";
// This works
echo 'var my_array = {' . $values .'}'; // outputs: var my_array
{0:'foo', 1:'bar'}
// This also works (note the spaces, we want the curly braces to be taken literally).
echo "var my_array = { $values }"; // outputs: var my_array = { 0:'foo',
1:'bar' }
// Doesn't work, the curly-braces get parsed and in this case we actually don't want that
echo "var my_array = {$values}"; // outputs: var my_array = 0:'foo',
1:'bar'
// Obviously doesn't work -- we need $values to be parsed
echo "var my_array = {\$values}"; // outputs: var my_array = {$values}
// Doesn't work -- { can't be escaped
echo "var my_array = \{$values}"; // outputs: var my_array \0:'foo',
1:'bar'
// But using ASCII values works
echo "var my_array = \x7B$values\x7D"; // outputs: var my_array = {0:'foo',
1:'bar'}
?>
The simplest solution in this example is to separate the { from the $ using whitespace.
----
Server IP: 69.147.83.197
Probable Submitter: 76.2.25.104
----
Manual Page -- http://www.php.net/manual/en/language.types.string.php
Edit -- https://master.php.net/note/edit/90241
Del: integrated -- https://master.php.net/note/delete/90241/integrated
Del: useless -- https://master.php.net/note/delete/90241/useless
Del: bad code -- https://master.php.net/note/delete/90241/bad+code
Del: spam -- https://master.php.net/note/delete/90241/spam
Del: non-english -- https://master.php.net/note/delete/90241/non-english
Del: in docs -- https://master.php.net/note/delete/90241/in+docs
Del: other reasons-- https://master.php.net/note/delete/90241
Reject -- https://master.php.net/note/reject/90241
Search -- https://master.php.net/manage/user-notes.php