我正在编写带有大量可变字符串串联的PHP代码,并且我想使用双引号,如果它们靠近变量,我将无法正确打印括号。
因此,这与预期一样的作用:
$first = 'Ani';
$second = 'ma';
$third = array( 'ing', 'ted', 'tion' );
$variable = "$first$second{$third[2]}";
echo $variable;
>> Animation
但是,如果我希望字符串中有括号文字,这就是我得到的:
$var1 = 'red';
$var2 = 'blue';
$var3 = 'green';
$variable = "x = {$var1,$var2,$var3}";
echo $variable
>> PHP Parse error: syntax error, unexpected token ",", expecting "->" or "?->" or "{" or "["
换句话说,PHP正在使用括号进行可变解析,但我只希望将其从字面上进行对待。当我逃脱括号时,它会打印,但是带有逃生字符:
$variable = "x = \{$var1,$var2,$var3\}";
echo $variable
>> x = \{red,blue,green\}
我有可能使用双引号并在变量旁边正确地打印出字面的括号打印吗?否则,这将使我的代码变得更加混乱和耗时。
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.
发布评论
评论(1)
将输出:
如果您需要以下内容:
X = {红色,绿色,蓝色}
您不能,因为{无法逃脱”。来源:
will output:
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