php将赢得逃脱括号

发布于 2025-01-25 05:04:52 字数 762 浏览 0 评论 0 原文

我正在编写带有大量可变字符串串联的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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

染年凉城似染瑾 2025-02-01 05:04:52
$var1 = 'red';
$var2 = 'blue';
$var3 = 'green';
$variable = "x = {\$var1,\$var2,\$var3}";
echo $variable;

将输出:

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

如果您需要以下内容:
X = {红色,绿色,蓝色}

您不能,因为{无法逃脱”。来源:

$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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文