PHP:字符串中的变量没有连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7036931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: variables in strings without concatenation
提问by lemon
If I have a variable $var in this string:
echo "Hello, there are many $vars";
如果我在这个字符串中有一个变量 $var:
echo "Hello, there are many $vars";
Php looks for the variable $vars
instead of $var
.
Php 寻找variable $vars
代替$var
。
Without concatenation like: "Hello, there are many $var" . "s";
is there another way to do this, like some sort of escaping character?
没有像这样的连接:"Hello, there are many $var" . "s";
有没有另一种方法可以做到这一点,比如某种转义字符?
回答by Tristan
回答by Madara's Ghost
You can use {}
to escape your variable properly. Consider the following example:
您可以使用{}
来正确转义您的变量。考虑以下示例:
echo "There are many ${var}s"; #Or...
echo "There are many {$var}s";
回答by Pelshoff
Alternatively you may want to look at sprintf: http://php.net/manual/en/function.sprintf.php
或者,您可能想查看 sprintf:http: //php.net/manual/en/function.sprintf.php
The sprintf function allows you to format any type of variable as a string in a specific notation.
sprintf 函数允许您将任何类型的变量格式化为特定符号中的字符串。
回答by Kokos
Personally I always divide the variables from a string like this: echo 'Hello, there are many '.$var.'s';
我个人总是从这样的字符串中划分变量: echo 'Hello, there are many '.$var.'s';
Mostly because of readability, if you go through your code it's instantly clear where the variables are.
主要是因为可读性,如果你仔细阅读你的代码,它会立即清楚变量在哪里。