Home > Software design >  PHP won't escape brackets if near variable in double quote
PHP won't escape brackets if near variable in double quote

Time:05-01

I am writing PHP code with a lot of variable string concatenations, and I'd like to use double quotes I can't get brackets to print right if they are next to a variable.

So, this works like expected:

$first = 'Ani';
$second = 'ma';
$third = array( 'ing', 'ted', 'tion' );
$variable = "$first$second{$third[2]}";
echo $variable;

>> Animation

But this is what I get if I want the string to have bracket literals in it:

$var1 = 'red';
$var2 = 'blue';
$var3 = 'green';
$variable = "x = {$var1,$var2,$var3}";
echo $variable

>> PHP Parse error:  syntax error, unexpected token ",", expecting "->" or "?->" or "{" or "["

In other words, PHP is using the brackets for variable parsing but I just want it to be treated literally. When I escape the brackets, it prints but with the escape character:

$variable = "x = \{$var1,$var2,$var3\}";
echo $variable

>> x = \{red,blue,green\}

Is it possible for me to use double quotes AND have a literal bracket print properly next to a variable? Otherwise, it will make my code a lot messier and time consuming to write.

CodePudding user response:

$var1 = 'red';
$var2 = 'blue';
$var3 = 'green';
$variable = "x = {\$var1,\$var2,\$var3}";
echo $variable;

will output:

x = {$var1,$var2,$var3}

If you need the following : x = {red,green,blue}

You can't, "Since { can not be escaped". Source: https://www.php.net/manual/en/language.types.string.php#language.types.string.parsing.complex

  • Related