note 90241 deleted from language.types.string by thiago

From: Date: Tue, 20 Oct 2009 12:44:19 +0000
Subject: note 90241 deleted from language.types.string by thiago
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-161899@lists.php.net to get a copy of this message
Note Submitter: strata_ranger at hotmail dot com ---- 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.

« previous php.notes (#161899) next »